blob: 7c9b32beda61426ff386d68b9bb5669fc051cad3 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.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#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
Todd Fiala6ac1be42014-08-21 16:34:03 +000021#if defined (__arm64__) || defined (__aarch64__)
22// NT_PRSTATUS and NT_FPREGSET definition
23#include <elf.h>
24#endif
25
Todd Fialaaf245d12014-06-30 21:05:18 +000026// C++ Includes
27#include <fstream>
28#include <string>
29
30// Other libraries and framework includes
31#include "lldb/Core/Debugger.h"
32#include "lldb/Core/Error.h"
33#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000034#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000035#include "lldb/Core/RegisterValue.h"
36#include "lldb/Core/Scalar.h"
37#include "lldb/Core/State.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000038#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000040#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000041#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000042#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000044#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "lldb/Target/ProcessLaunchInfo.h"
46#include "lldb/Utility/PseudoTerminal.h"
47
Chaoren Lin2fe1d0a2015-02-03 01:51:38 +000048#include "lldb/Host/common/NativeBreakpoint.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049#include "Utility/StringExtractor.h"
50
51#include "Plugins/Process/Utility/LinuxSignals.h"
52#include "NativeThreadLinux.h"
53#include "ProcFileReader.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000054#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000055#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
56
Tamas Berghammerd8584872015-02-06 10:57:40 +000057// System includes - They have to be included after framework includes because they define some
58// macros which collide with variable names in other modules
59#include <linux/unistd.h>
60#ifndef __ANDROID__
61#include <sys/procfs.h>
62#endif
63#include <sys/personality.h>
64#include <sys/ptrace.h>
65#include <sys/socket.h>
66#include <sys/syscall.h>
67#include <sys/types.h>
68#include <sys/uio.h>
69#include <sys/user.h>
70#include <sys/wait.h>
71
Todd Fialacacde7d2014-09-27 16:54:22 +000072#ifdef __ANDROID__
73#define __ptrace_request int
74#define PT_DETACH PTRACE_DETACH
75#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000076
77#define DEBUG_PTRACE_MAXBYTES 20
78
79// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000080#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000081#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000082 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000083#endif
Todd Fialadda61942014-07-02 21:34:04 +000084#endif
85#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000086#ifndef PTRACE_SETREGS
87 #define PTRACE_SETREGS 13
88#endif
Todd Fialadda61942014-07-02 21:34:04 +000089#endif
90#ifndef PT_GETFPREGS
91#ifndef PTRACE_GETFPREGS
92 #define PTRACE_GETFPREGS 14
93#endif
94#endif
95#ifndef PT_SETFPREGS
96#ifndef PTRACE_SETFPREGS
97 #define PTRACE_SETFPREGS 15
98#endif
99#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000100#ifndef PTRACE_GETREGSET
101 #define PTRACE_GETREGSET 0x4204
102#endif
103#ifndef PTRACE_SETREGSET
104 #define PTRACE_SETREGSET 0x4205
105#endif
106#ifndef PTRACE_GET_THREAD_AREA
107 #define PTRACE_GET_THREAD_AREA 25
108#endif
109#ifndef PTRACE_ARCH_PRCTL
110 #define PTRACE_ARCH_PRCTL 30
111#endif
112#ifndef ARCH_GET_FS
113 #define ARCH_SET_GS 0x1001
114 #define ARCH_SET_FS 0x1002
115 #define ARCH_GET_FS 0x1003
116 #define ARCH_GET_GS 0x1004
117#endif
118
Todd Fiala0bce1b62014-08-17 00:10:50 +0000119#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121// Support hardware breakpoints in case it has not been defined
122#ifndef TRAP_HWBKPT
123 #define TRAP_HWBKPT 4
124#endif
125
126// Try to define a macro to encapsulate the tgkill syscall
127// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000128#define tgkill(pid, tid, sig) \
129 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000130
131// We disable the tracing of ptrace calls for integration builds to
132// avoid the additional indirection and checks.
133#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000134#define PTRACE(req, pid, addr, data, data_size, error) \
135 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000136#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000137#define PTRACE(req, pid, addr, data, data_size, error) \
138 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000139#endif
140
141// Private bits we only need internally.
142namespace
143{
144 using namespace lldb;
145 using namespace lldb_private;
146
Tamas Berghammer43f2d972015-03-04 11:10:03 +0000147 static void * const EXIT_OPERATION = nullptr;
148
Todd Fialaaf245d12014-06-30 21:05:18 +0000149 const UnixSignals&
150 GetUnixSignals ()
151 {
152 static process_linux::LinuxSignals signals;
153 return signals;
154 }
155
Chaoren Linfa03ad22015-02-03 01:50:42 +0000156 ThreadStateCoordinator::LogFunction
157 GetThreadLoggerFunction ()
158 {
159 return [](const char *format, va_list args)
160 {
161 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
162 if (log)
163 log->VAPrintf (format, args);
164 };
165 }
166
167 void
168 CoordinatorErrorHandler (const std::string &error_message)
169 {
170 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
171 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000172 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000173 assert (false && "ThreadStateCoordinator error reported");
174 }
175
Todd Fialaaf245d12014-06-30 21:05:18 +0000176 Error
177 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
178 {
179 // Grab process info for the running process.
180 ProcessInstanceInfo process_info;
181 if (!platform.GetProcessInfo (pid, process_info))
182 return lldb_private::Error("failed to get process info");
183
184 // Resolve the executable module.
185 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000186 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000187 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
188 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000189 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000190 exe_module_sp,
191 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
192
193 if (!error.Success ())
194 return error;
195
196 // Check if we've got our architecture from the exe_module.
197 arch = exe_module_sp->GetArchitecture ();
198 if (arch.IsValid ())
199 return Error();
200 else
201 return Error("failed to retrieve a valid architecture from the exe module");
202 }
203
204 void
205 DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
206 {
207 uint8_t *ptr = (uint8_t *)bytes;
208 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
209 for(uint32_t i=0; i<loop_count; i++)
210 {
211 s.Printf ("[%x]", *ptr);
212 ptr++;
213 }
214 }
215
216 void
217 PtraceDisplayBytes(int &req, void *data, size_t data_size)
218 {
219 StreamString buf;
220 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
221 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
222
223 if (verbose_log)
224 {
225 switch(req)
226 {
227 case PTRACE_POKETEXT:
228 {
229 DisplayBytes(buf, &data, 8);
230 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
231 break;
232 }
233 case PTRACE_POKEDATA:
234 {
235 DisplayBytes(buf, &data, 8);
236 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
237 break;
238 }
239 case PTRACE_POKEUSER:
240 {
241 DisplayBytes(buf, &data, 8);
242 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
243 break;
244 }
245 case PTRACE_SETREGS:
246 {
247 DisplayBytes(buf, data, data_size);
248 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
249 break;
250 }
251 case PTRACE_SETFPREGS:
252 {
253 DisplayBytes(buf, data, data_size);
254 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
255 break;
256 }
257 case PTRACE_SETSIGINFO:
258 {
259 DisplayBytes(buf, data, sizeof(siginfo_t));
260 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
261 break;
262 }
263 case PTRACE_SETREGSET:
264 {
265 // Extract iov_base from data, which is a pointer to the struct IOVEC
266 DisplayBytes(buf, *(void **)data, data_size);
267 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
268 break;
269 }
270 default:
271 {
272 }
273 }
274 }
275 }
276
277 // Wrapper for ptrace to catch errors and log calls.
278 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
279 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000280 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
281 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000282 {
283 long int result;
284
285 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
286
287 PtraceDisplayBytes(req, data, data_size);
288
Chaoren Lin97ccc292015-02-03 01:51:12 +0000289 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 errno = 0;
291 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000292 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000293 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000294 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000295
Chaoren Lin97ccc292015-02-03 01:51:12 +0000296 if (result == -1)
297 error.SetErrorToErrno();
298
Todd Fialaaf245d12014-06-30 21:05:18 +0000299 if (log)
300 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
301 reqName, pid, addr, data, data_size, result, file, line);
302
303 PtraceDisplayBytes(req, data, data_size);
304
Chaoren Lin97ccc292015-02-03 01:51:12 +0000305 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 {
307 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000308 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000309 {
310 case ESRCH: str = "ESRCH"; break;
311 case EINVAL: str = "EINVAL"; break;
312 case EBUSY: str = "EBUSY"; break;
313 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000314 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000315 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000316 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000317 }
318
319 return result;
320 }
321
322#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
323 // Wrapper for ptrace when logging is not required.
324 // Sets errno to 0 prior to calling ptrace.
325 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000326 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000327 {
328 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000329
330 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 errno = 0;
332 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000333 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000335 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000336
337 if (result == -1)
338 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000339 return result;
340 }
341#endif
342
343 //------------------------------------------------------------------------------
344 // Static implementations of NativeProcessLinux::ReadMemory and
345 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
346 // functions without needed to go thru the thread funnel.
347
Chaoren Lin97ccc292015-02-03 01:51:12 +0000348 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000349 DoReadMemory (
350 lldb::pid_t pid,
351 lldb::addr_t vm_addr,
352 void *buf,
353 lldb::addr_t size,
354 Error &error)
355 {
356 // ptrace word size is determined by the host, not the child
357 static const unsigned word_size = sizeof(void*);
358 unsigned char *dst = static_cast<unsigned char*>(buf);
359 lldb::addr_t bytes_read;
360 lldb::addr_t remainder;
361 long data;
362
363 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
364 if (log)
365 ProcessPOSIXLog::IncNestLevel();
366 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
367 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
368 pid, word_size, (void*)vm_addr, buf, size);
369
370 assert(sizeof(data) >= word_size);
371 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
372 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000373 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
374 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000376 if (log)
377 ProcessPOSIXLog::DecNestLevel();
378 return bytes_read;
379 }
380
381 remainder = size - bytes_read;
382 remainder = remainder > word_size ? word_size : remainder;
383
384 // Copy the data into our buffer
385 for (unsigned i = 0; i < remainder; ++i)
386 dst[i] = ((data >> i*8) & 0xFF);
387
388 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
389 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
390 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
391 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
392 {
393 uintptr_t print_dst = 0;
394 // Format bytes from data by moving into print_dst for log output
395 for (unsigned i = 0; i < remainder; ++i)
396 print_dst |= (((data >> i*8) & 0xFF) << i*8);
397 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
398 (void*)vm_addr, print_dst, (unsigned long)data);
399 }
400
401 vm_addr += word_size;
402 dst += word_size;
403 }
404
405 if (log)
406 ProcessPOSIXLog::DecNestLevel();
407 return bytes_read;
408 }
409
Chaoren Lin97ccc292015-02-03 01:51:12 +0000410 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000411 DoWriteMemory(
412 lldb::pid_t pid,
413 lldb::addr_t vm_addr,
414 const void *buf,
415 lldb::addr_t size,
416 Error &error)
417 {
418 // ptrace word size is determined by the host, not the child
419 static const unsigned word_size = sizeof(void*);
420 const unsigned char *src = static_cast<const unsigned char*>(buf);
421 lldb::addr_t bytes_written = 0;
422 lldb::addr_t remainder;
423
424 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
425 if (log)
426 ProcessPOSIXLog::IncNestLevel();
427 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
428 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
429 pid, word_size, (void*)vm_addr, buf, size);
430
431 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
432 {
433 remainder = size - bytes_written;
434 remainder = remainder > word_size ? word_size : remainder;
435
436 if (remainder == word_size)
437 {
438 unsigned long data = 0;
439 assert(sizeof(data) >= word_size);
440 for (unsigned i = 0; i < word_size; ++i)
441 data |= (unsigned long)src[i] << i*8;
442
443 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
446 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
447 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
448 (void*)vm_addr, *(unsigned long*)src, data);
449
Chaoren Lin97ccc292015-02-03 01:51:12 +0000450 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000451 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 if (log)
453 ProcessPOSIXLog::DecNestLevel();
454 return bytes_written;
455 }
456 }
457 else
458 {
459 unsigned char buff[8];
460 if (DoReadMemory(pid, vm_addr,
461 buff, word_size, error) != word_size)
462 {
463 if (log)
464 ProcessPOSIXLog::DecNestLevel();
465 return bytes_written;
466 }
467
468 memcpy(buff, src, remainder);
469
470 if (DoWriteMemory(pid, vm_addr,
471 buff, word_size, error) != word_size)
472 {
473 if (log)
474 ProcessPOSIXLog::DecNestLevel();
475 return bytes_written;
476 }
477
478 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
479 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
480 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
481 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
482 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
483 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
484 }
485
486 vm_addr += word_size;
487 src += word_size;
488 }
489 if (log)
490 ProcessPOSIXLog::DecNestLevel();
491 return bytes_written;
492 }
493
494 //------------------------------------------------------------------------------
495 /// @class Operation
496 /// @brief Represents a NativeProcessLinux operation.
497 ///
498 /// Under Linux, it is not possible to ptrace() from any other thread but the
499 /// one that spawned or attached to the process from the start. Therefore, when
500 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
501 /// process the operation must be "funneled" to a specific thread to perform the
502 /// task. The Operation class provides an abstract base for all services the
503 /// NativeProcessLinux must perform via the single virtual function Execute, thus
504 /// encapsulating the code that needs to run in the privileged context.
505 class Operation
506 {
507 public:
508 Operation () : m_error() { }
509
510 virtual
511 ~Operation() {}
512
513 virtual void
514 Execute (NativeProcessLinux *process) = 0;
515
516 const Error &
517 GetError () const { return m_error; }
518
519 protected:
520 Error m_error;
521 };
522
523 //------------------------------------------------------------------------------
524 /// @class ReadOperation
525 /// @brief Implements NativeProcessLinux::ReadMemory.
526 class ReadOperation : public Operation
527 {
528 public:
529 ReadOperation (
530 lldb::addr_t addr,
531 void *buff,
532 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000533 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000534 Operation (),
535 m_addr (addr),
536 m_buff (buff),
537 m_size (size),
538 m_result (result)
539 {
540 }
541
542 void Execute (NativeProcessLinux *process) override;
543
544 private:
545 lldb::addr_t m_addr;
546 void *m_buff;
547 lldb::addr_t m_size;
548 lldb::addr_t &m_result;
549 };
550
551 void
552 ReadOperation::Execute (NativeProcessLinux *process)
553 {
554 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
555 }
556
557 //------------------------------------------------------------------------------
558 /// @class WriteOperation
559 /// @brief Implements NativeProcessLinux::WriteMemory.
560 class WriteOperation : public Operation
561 {
562 public:
563 WriteOperation (
564 lldb::addr_t addr,
565 const void *buff,
566 lldb::addr_t size,
567 lldb::addr_t &result) :
568 Operation (),
569 m_addr (addr),
570 m_buff (buff),
571 m_size (size),
572 m_result (result)
573 {
574 }
575
576 void Execute (NativeProcessLinux *process) override;
577
578 private:
579 lldb::addr_t m_addr;
580 const void *m_buff;
581 lldb::addr_t m_size;
582 lldb::addr_t &m_result;
583 };
584
585 void
586 WriteOperation::Execute(NativeProcessLinux *process)
587 {
588 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
589 }
590
591 //------------------------------------------------------------------------------
592 /// @class ReadRegOperation
593 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
594 class ReadRegOperation : public Operation
595 {
596 public:
597 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000598 RegisterValue &value)
599 : m_tid(tid),
600 m_offset(static_cast<uintptr_t> (offset)),
601 m_reg_name(reg_name),
602 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000603 { }
604
605 void Execute(NativeProcessLinux *monitor);
606
607 private:
608 lldb::tid_t m_tid;
609 uintptr_t m_offset;
610 const char *m_reg_name;
611 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 };
613
614 void
615 ReadRegOperation::Execute(NativeProcessLinux *monitor)
616 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000617#if defined (__arm64__) || defined (__aarch64__)
618 if (m_offset > sizeof(struct user_pt_regs))
619 {
620 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
621 if (offset > sizeof(struct user_fpsimd_state))
622 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000623 m_error.SetErrorString("invalid offset value");
624 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000625 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000626 elf_fpregset_t regs;
627 int regset = NT_FPREGSET;
628 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000629
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 ioVec.iov_base = &regs;
631 ioVec.iov_len = sizeof regs;
632 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
633 if (m_error.Success())
634 {
635 lldb_private::ArchSpec arch;
636 if (monitor->GetArchitecture(arch))
637 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000638 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000639 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000640 }
641 }
642 else
643 {
644 elf_gregset_t regs;
645 int regset = NT_PRSTATUS;
646 struct iovec ioVec;
647
648 ioVec.iov_base = &regs;
649 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000650 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
651 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000652 {
653 lldb_private::ArchSpec arch;
654 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000656 else
657 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000658 }
659 }
660#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000661 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
662
Chaoren Lin97ccc292015-02-03 01:51:12 +0000663 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error);
664 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000665 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000666
Todd Fialaaf245d12014-06-30 21:05:18 +0000667 if (log)
668 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
669 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000670#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000671 }
672
673 //------------------------------------------------------------------------------
674 /// @class WriteRegOperation
675 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
676 class WriteRegOperation : public Operation
677 {
678 public:
679 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000680 const RegisterValue &value)
681 : m_tid(tid),
682 m_offset(offset),
683 m_reg_name(reg_name),
684 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 { }
686
687 void Execute(NativeProcessLinux *monitor);
688
689 private:
690 lldb::tid_t m_tid;
691 uintptr_t m_offset;
692 const char *m_reg_name;
693 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000694 };
695
696 void
697 WriteRegOperation::Execute(NativeProcessLinux *monitor)
698 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000699#if defined (__arm64__) || defined (__aarch64__)
700 if (m_offset > sizeof(struct user_pt_regs))
701 {
702 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
703 if (offset > sizeof(struct user_fpsimd_state))
704 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000705 m_error.SetErrorString("invalid offset value");
706 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000707 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000708 elf_fpregset_t regs;
709 int regset = NT_FPREGSET;
710 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000711
Chaoren Lin97ccc292015-02-03 01:51:12 +0000712 ioVec.iov_base = &regs;
713 ioVec.iov_len = sizeof regs;
714 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000715 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000716 {
717 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
718 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000719 }
720 }
721 else
722 {
723 elf_gregset_t regs;
724 int regset = NT_PRSTATUS;
725 struct iovec ioVec;
726
727 ioVec.iov_base = &regs;
728 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000729 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000730 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000731 {
732 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000733 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000734 }
735 }
736#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000737 void* buf;
738 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
739
740 buf = (void*) m_value.GetAsUInt64();
741
742 if (log)
743 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000744 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000745#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000746 }
747
748 //------------------------------------------------------------------------------
749 /// @class ReadGPROperation
750 /// @brief Implements NativeProcessLinux::ReadGPR.
751 class ReadGPROperation : public Operation
752 {
753 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000754 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
755 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 { }
757
758 void Execute(NativeProcessLinux *monitor);
759
760 private:
761 lldb::tid_t m_tid;
762 void *m_buf;
763 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000764 };
765
766 void
767 ReadGPROperation::Execute(NativeProcessLinux *monitor)
768 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000769#if defined (__arm64__) || defined (__aarch64__)
770 int regset = NT_PRSTATUS;
771 struct iovec ioVec;
772
773 ioVec.iov_base = m_buf;
774 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000775 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000776#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000777 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000778#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000779 }
780
781 //------------------------------------------------------------------------------
782 /// @class ReadFPROperation
783 /// @brief Implements NativeProcessLinux::ReadFPR.
784 class ReadFPROperation : public Operation
785 {
786 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000787 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
788 : m_tid(tid),
789 m_buf(buf),
790 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000791 { }
792
793 void Execute(NativeProcessLinux *monitor);
794
795 private:
796 lldb::tid_t m_tid;
797 void *m_buf;
798 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000799 };
800
801 void
802 ReadFPROperation::Execute(NativeProcessLinux *monitor)
803 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000804#if defined (__arm64__) || defined (__aarch64__)
805 int regset = NT_FPREGSET;
806 struct iovec ioVec;
807
808 ioVec.iov_base = m_buf;
809 ioVec.iov_len = m_buf_size;
810 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
811 m_result = false;
812 else
813 m_result = true;
814#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000815 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000816#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000817 }
818
819 //------------------------------------------------------------------------------
820 /// @class ReadRegisterSetOperation
821 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
822 class ReadRegisterSetOperation : public Operation
823 {
824 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000825 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
826 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000827 { }
828
829 void Execute(NativeProcessLinux *monitor);
830
831 private:
832 lldb::tid_t m_tid;
833 void *m_buf;
834 size_t m_buf_size;
835 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000836 };
837
838 void
839 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
840 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000841 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000842 }
843
844 //------------------------------------------------------------------------------
845 /// @class WriteGPROperation
846 /// @brief Implements NativeProcessLinux::WriteGPR.
847 class WriteGPROperation : public Operation
848 {
849 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000850 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
851 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000852 { }
853
854 void Execute(NativeProcessLinux *monitor);
855
856 private:
857 lldb::tid_t m_tid;
858 void *m_buf;
859 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000860 };
861
862 void
863 WriteGPROperation::Execute(NativeProcessLinux *monitor)
864 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000865#if defined (__arm64__) || defined (__aarch64__)
866 int regset = NT_PRSTATUS;
867 struct iovec ioVec;
868
869 ioVec.iov_base = m_buf;
870 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000871 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000872#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000873 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000874#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000875 }
876
877 //------------------------------------------------------------------------------
878 /// @class WriteFPROperation
879 /// @brief Implements NativeProcessLinux::WriteFPR.
880 class WriteFPROperation : public Operation
881 {
882 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000883 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
884 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000885 { }
886
887 void Execute(NativeProcessLinux *monitor);
888
889 private:
890 lldb::tid_t m_tid;
891 void *m_buf;
892 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000893 };
894
895 void
896 WriteFPROperation::Execute(NativeProcessLinux *monitor)
897 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000898#if defined (__arm64__) || defined (__aarch64__)
899 int regset = NT_FPREGSET;
900 struct iovec ioVec;
901
902 ioVec.iov_base = m_buf;
903 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000904 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000905#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000906 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000907#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000908 }
909
910 //------------------------------------------------------------------------------
911 /// @class WriteRegisterSetOperation
912 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
913 class WriteRegisterSetOperation : public Operation
914 {
915 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000916 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
917 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000918 { }
919
920 void Execute(NativeProcessLinux *monitor);
921
922 private:
923 lldb::tid_t m_tid;
924 void *m_buf;
925 size_t m_buf_size;
926 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000927 };
928
929 void
930 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
931 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000932 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000933 }
934
935 //------------------------------------------------------------------------------
936 /// @class ResumeOperation
937 /// @brief Implements NativeProcessLinux::Resume.
938 class ResumeOperation : public Operation
939 {
940 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000941 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
942 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000943
944 void Execute(NativeProcessLinux *monitor);
945
946 private:
947 lldb::tid_t m_tid;
948 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000949 };
950
951 void
952 ResumeOperation::Execute(NativeProcessLinux *monitor)
953 {
954 intptr_t data = 0;
955
956 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
957 data = m_signo;
958
Chaoren Lin97ccc292015-02-03 01:51:12 +0000959 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
960 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000961 {
962 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
963
964 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000965 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000966 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000967 }
968
969 //------------------------------------------------------------------------------
970 /// @class SingleStepOperation
971 /// @brief Implements NativeProcessLinux::SingleStep.
972 class SingleStepOperation : public Operation
973 {
974 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000975 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
976 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000977
978 void Execute(NativeProcessLinux *monitor);
979
980 private:
981 lldb::tid_t m_tid;
982 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000983 };
984
985 void
986 SingleStepOperation::Execute(NativeProcessLinux *monitor)
987 {
988 intptr_t data = 0;
989
990 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
991 data = m_signo;
992
Chaoren Lin97ccc292015-02-03 01:51:12 +0000993 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000994 }
995
996 //------------------------------------------------------------------------------
997 /// @class SiginfoOperation
998 /// @brief Implements NativeProcessLinux::GetSignalInfo.
999 class SiginfoOperation : public Operation
1000 {
1001 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001002 SiginfoOperation(lldb::tid_t tid, void *info)
1003 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001004
1005 void Execute(NativeProcessLinux *monitor);
1006
1007 private:
1008 lldb::tid_t m_tid;
1009 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001010 };
1011
1012 void
1013 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1014 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001015 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001016 }
1017
1018 //------------------------------------------------------------------------------
1019 /// @class EventMessageOperation
1020 /// @brief Implements NativeProcessLinux::GetEventMessage.
1021 class EventMessageOperation : public Operation
1022 {
1023 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001024 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1025 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001026
1027 void Execute(NativeProcessLinux *monitor);
1028
1029 private:
1030 lldb::tid_t m_tid;
1031 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 };
1033
1034 void
1035 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1036 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001037 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001038 }
1039
1040 class DetachOperation : public Operation
1041 {
1042 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001043 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001044
1045 void Execute(NativeProcessLinux *monitor);
1046
1047 private:
1048 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001049 };
1050
1051 void
1052 DetachOperation::Execute(NativeProcessLinux *monitor)
1053 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001054 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001055 }
1056
1057}
1058
1059using namespace lldb_private;
1060
1061// Simple helper function to ensure flags are enabled on the given file
1062// descriptor.
1063static bool
1064EnsureFDFlags(int fd, int flags, Error &error)
1065{
1066 int status;
1067
1068 if ((status = fcntl(fd, F_GETFL)) == -1)
1069 {
1070 error.SetErrorToErrno();
1071 return false;
1072 }
1073
1074 if (fcntl(fd, F_SETFL, status | flags) == -1)
1075 {
1076 error.SetErrorToErrno();
1077 return false;
1078 }
1079
1080 return true;
1081}
1082
1083NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1084 : m_monitor(monitor)
1085{
1086 sem_init(&m_semaphore, 0, 0);
1087}
1088
1089NativeProcessLinux::OperationArgs::~OperationArgs()
1090{
1091 sem_destroy(&m_semaphore);
1092}
1093
1094NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
1095 lldb_private::Module *module,
1096 char const **argv,
1097 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001098 const std::string &stdin_path,
1099 const std::string &stdout_path,
1100 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001101 const char *working_dir,
1102 const lldb_private::ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001103 : OperationArgs(monitor),
1104 m_module(module),
1105 m_argv(argv),
1106 m_envp(envp),
1107 m_stdin_path(stdin_path),
1108 m_stdout_path(stdout_path),
1109 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001110 m_working_dir(working_dir),
1111 m_launch_info(launch_info)
1112{
1113}
Todd Fialaaf245d12014-06-30 21:05:18 +00001114
1115NativeProcessLinux::LaunchArgs::~LaunchArgs()
1116{ }
1117
1118NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1119 lldb::pid_t pid)
1120 : OperationArgs(monitor), m_pid(pid) { }
1121
1122NativeProcessLinux::AttachArgs::~AttachArgs()
1123{ }
1124
1125// -----------------------------------------------------------------------------
1126// Public Static Methods
1127// -----------------------------------------------------------------------------
1128
1129lldb_private::Error
1130NativeProcessLinux::LaunchProcess (
1131 lldb_private::Module *exe_module,
1132 lldb_private::ProcessLaunchInfo &launch_info,
1133 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1134 NativeProcessProtocolSP &native_process_sp)
1135{
1136 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1137
1138 Error error;
1139
1140 // Verify the working directory is valid if one was specified.
1141 const char* working_dir = launch_info.GetWorkingDirectory ();
1142 if (working_dir)
1143 {
1144 FileSpec working_dir_fs (working_dir, true);
1145 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1146 {
1147 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1148 return error;
1149 }
1150 }
1151
Zachary Turner696b5282014-08-14 16:01:25 +00001152 const lldb_private::FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001153
1154 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001155 std::string stdin_path;
1156 std::string stdout_path;
1157 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001158
1159 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001160 if (file_action)
1161 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001162
1163 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001164 if (file_action)
1165 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001166
1167 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001168 if (file_action)
1169 stderr_path = file_action->GetPath ();
1170
1171 if (log)
1172 {
1173 if (!stdin_path.empty ())
1174 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1175 else
1176 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1177
1178 if (!stdout_path.empty ())
1179 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1180 else
1181 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1182
1183 if (!stderr_path.empty ())
1184 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1185 else
1186 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1187 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001188
1189 // Create the NativeProcessLinux in launch mode.
1190 native_process_sp.reset (new NativeProcessLinux ());
1191
1192 if (log)
1193 {
1194 int i = 0;
1195 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1196 {
1197 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1198 ++i;
1199 }
1200 }
1201
1202 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1203 {
1204 native_process_sp.reset ();
1205 error.SetErrorStringWithFormat ("failed to register the native delegate");
1206 return error;
1207 }
1208
1209 reinterpret_cast<NativeProcessLinux*> (native_process_sp.get ())->LaunchInferior (
1210 exe_module,
1211 launch_info.GetArguments ().GetConstArgumentVector (),
1212 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1213 stdin_path,
1214 stdout_path,
1215 stderr_path,
1216 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001217 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001218 error);
1219
1220 if (error.Fail ())
1221 {
1222 native_process_sp.reset ();
1223 if (log)
1224 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1225 return error;
1226 }
1227
1228 launch_info.SetProcessID (native_process_sp->GetID ());
1229
1230 return error;
1231}
1232
1233lldb_private::Error
1234NativeProcessLinux::AttachToProcess (
1235 lldb::pid_t pid,
1236 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1237 NativeProcessProtocolSP &native_process_sp)
1238{
1239 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1240 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1241 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1242
1243 // Grab the current platform architecture. This should be Linux,
1244 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001245 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001246 if (!platform_sp)
1247 return Error("failed to get a valid default platform");
1248
1249 // Retrieve the architecture for the running process.
1250 ArchSpec process_arch;
1251 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1252 if (!error.Success ())
1253 return error;
1254
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001255 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001256
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001257 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001258 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 error.SetErrorStringWithFormat ("failed to register the native delegate");
1260 return error;
1261 }
1262
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001263 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001264 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001265 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001266
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001267 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001268 return error;
1269}
1270
1271// -----------------------------------------------------------------------------
1272// Public Instance Methods
1273// -----------------------------------------------------------------------------
1274
1275NativeProcessLinux::NativeProcessLinux () :
1276 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1277 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001278 m_operation_thread (),
1279 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001280 m_operation (nullptr),
1281 m_operation_mutex (),
1282 m_operation_pending (),
1283 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001284 m_supports_mem_region (eLazyBoolCalculate),
1285 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001286 m_mem_region_cache_mutex (),
1287 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1288 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001289{
1290}
1291
1292//------------------------------------------------------------------------------
1293/// The basic design of the NativeProcessLinux is built around two threads.
1294///
1295/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1296/// for changes in the debugee state. When a change is detected a
1297/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1298/// "drives" state changes in the debugger.
1299///
1300/// The second thread (@see OperationThread) is responsible for two things 1)
1301/// launching or attaching to the inferior process, and then 2) servicing
1302/// operations such as register reads/writes, stepping, etc. See the comments
1303/// on the Operation class for more info as to why this is needed.
1304void
1305NativeProcessLinux::LaunchInferior (
1306 Module *module,
1307 const char *argv[],
1308 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001309 const std::string &stdin_path,
1310 const std::string &stdout_path,
1311 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001312 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001313 const lldb_private::ProcessLaunchInfo &launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001314 lldb_private::Error &error)
1315{
1316 if (module)
1317 m_arch = module->GetArchitecture ();
1318
Chaoren Linfa03ad22015-02-03 01:50:42 +00001319 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001320
1321 std::unique_ptr<LaunchArgs> args(
1322 new LaunchArgs(
1323 this, module, argv, envp,
1324 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001325 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001326
Chaoren Linfa03ad22015-02-03 01:50:42 +00001327 sem_init (&m_operation_pending, 0, 0);
1328 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001329
Chaoren Linfa03ad22015-02-03 01:50:42 +00001330 StartLaunchOpThread (args.get(), error);
1331 if (!error.Success ())
1332 return;
1333
1334 error = StartCoordinatorThread ();
1335 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001336 return;
1337
1338WAIT_AGAIN:
1339 // Wait for the operation thread to initialize.
1340 if (sem_wait(&args->m_semaphore))
1341 {
1342 if (errno == EINTR)
1343 goto WAIT_AGAIN;
1344 else
1345 {
1346 error.SetErrorToErrno();
1347 return;
1348 }
1349 }
1350
1351 // Check that the launch was a success.
1352 if (!args->m_error.Success())
1353 {
1354 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001355 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001356 error = args->m_error;
1357 return;
1358 }
1359
1360 // Finally, start monitoring the child process for change in state.
1361 m_monitor_thread = Host::StartMonitoringChildProcess(
1362 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001363 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001364 {
1365 error.SetErrorToGenericError();
1366 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1367 return;
1368 }
1369}
1370
1371void
1372NativeProcessLinux::AttachToInferior (lldb::pid_t pid, lldb_private::Error &error)
1373{
1374 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1375 if (log)
1376 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1377
1378 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001379 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001380 if (!platform_sp)
1381 {
1382 if (log)
1383 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1384 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001385 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001386 }
1387
1388 // Gather info about the process.
1389 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001390 if (!platform_sp->GetProcessInfo (pid, process_info))
1391 {
1392 if (log)
1393 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1394 error.SetErrorString ("failed to get process info");
1395 return;
1396 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001397
1398 // Resolve the executable module
1399 ModuleSP exe_module_sp;
1400 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001401 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001402 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001403 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001404 if (!error.Success())
1405 return;
1406
1407 // Set the architecture to the exe architecture.
1408 m_arch = exe_module_sp->GetArchitecture();
1409 if (log)
1410 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1411
1412 m_pid = pid;
1413 SetState(eStateAttaching);
1414
1415 sem_init (&m_operation_pending, 0, 0);
1416 sem_init (&m_operation_done, 0, 0);
1417
1418 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1419
1420 StartAttachOpThread(args.get (), error);
1421 if (!error.Success ())
1422 return;
1423
Chaoren Linfa03ad22015-02-03 01:50:42 +00001424 error = StartCoordinatorThread ();
1425 if (!error.Success ())
1426 return;
1427
Todd Fialaaf245d12014-06-30 21:05:18 +00001428WAIT_AGAIN:
1429 // Wait for the operation thread to initialize.
1430 if (sem_wait (&args->m_semaphore))
1431 {
1432 if (errno == EINTR)
1433 goto WAIT_AGAIN;
1434 else
1435 {
1436 error.SetErrorToErrno ();
1437 return;
1438 }
1439 }
1440
1441 // Check that the attach was a success.
1442 if (!args->m_error.Success ())
1443 {
1444 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001445 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001446 error = args->m_error;
1447 return;
1448 }
1449
1450 // Finally, start monitoring the child process for change in state.
1451 m_monitor_thread = Host::StartMonitoringChildProcess (
1452 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001453 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001454 {
1455 error.SetErrorToGenericError ();
1456 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1457 return;
1458 }
1459}
1460
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001461void
1462NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001463{
1464 StopMonitor();
1465}
1466
1467//------------------------------------------------------------------------------
1468// Thread setup and tear down.
1469
1470void
1471NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1472{
1473 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1474
Zachary Turneracee96a2014-09-23 18:32:09 +00001475 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001476 return;
1477
Zachary Turner39de3112014-09-09 20:54:56 +00001478 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001479}
1480
1481void *
1482NativeProcessLinux::LaunchOpThread(void *arg)
1483{
1484 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1485
1486 if (!Launch(args)) {
1487 sem_post(&args->m_semaphore);
1488 return NULL;
1489 }
1490
1491 ServeOperation(args);
1492 return NULL;
1493}
1494
1495bool
1496NativeProcessLinux::Launch(LaunchArgs *args)
1497{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001498 assert (args && "null args");
1499 if (!args)
1500 return false;
1501
Todd Fialaaf245d12014-06-30 21:05:18 +00001502 NativeProcessLinux *monitor = args->m_monitor;
1503 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001504
1505 const char **argv = args->m_argv;
1506 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001507 const char *working_dir = args->m_working_dir;
1508
1509 lldb_utility::PseudoTerminal terminal;
1510 const size_t err_len = 1024;
1511 char err_str[err_len];
1512 lldb::pid_t pid;
1513 NativeThreadProtocolSP thread_sp;
1514
1515 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001516
1517 // Propagate the environment if one is not supplied.
1518 if (envp == NULL || envp[0] == NULL)
1519 envp = const_cast<const char **>(environ);
1520
1521 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1522 {
1523 args->m_error.SetErrorToGenericError();
1524 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001525 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001526 }
1527
1528 // Recognized child exit status codes.
1529 enum {
1530 ePtraceFailed = 1,
1531 eDupStdinFailed,
1532 eDupStdoutFailed,
1533 eDupStderrFailed,
1534 eChdirFailed,
1535 eExecFailed,
1536 eSetGidFailed
1537 };
1538
1539 // Child process.
1540 if (pid == 0)
1541 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001542 // FIXME consider opening a pipe between parent/child and have this forked child
1543 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001544
Todd Fiala75f47c32014-10-11 21:42:09 +00001545 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001546 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1547 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001548 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001549
Pavel Labath493c3a12015-02-04 10:36:57 +00001550 // terminal has already dupped the tty descriptors to stdin/out/err.
1551 // This closes original fd from which they were copied (and avoids
1552 // leaking descriptors to the debugged process.
1553 terminal.CloseSlaveFileDescriptor();
1554
Todd Fialaaf245d12014-06-30 21:05:18 +00001555 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001556 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001557 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001558
1559 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001560 if (setpgid(0, 0) != 0)
1561 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001562 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001563 // Don't allow this to prevent an inferior exec.
1564 }
1565
1566 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001567 if (!args->m_stdin_path.empty ())
1568 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001569 exit(eDupStdinFailed);
1570
Todd Fiala75f47c32014-10-11 21:42:09 +00001571 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001572 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001573 exit(eDupStdoutFailed);
1574
Todd Fiala75f47c32014-10-11 21:42:09 +00001575 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001576 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 exit(eDupStderrFailed);
1578
1579 // Change working directory
1580 if (working_dir != NULL && working_dir[0])
1581 if (0 != ::chdir(working_dir))
1582 exit(eChdirFailed);
1583
Todd Fiala0bce1b62014-08-17 00:10:50 +00001584 // Disable ASLR if requested.
1585 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1586 {
1587 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1588 if (old_personality == -1)
1589 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001590 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001591 }
1592 else
1593 {
1594 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1595 if (new_personality == -1)
1596 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001597 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001598 }
1599 else
1600 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001601 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001602 }
1603 }
1604 }
1605
Todd Fiala75f47c32014-10-11 21:42:09 +00001606 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001607 execve(argv[0],
1608 const_cast<char *const *>(argv),
1609 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001610
1611 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001612 exit(eExecFailed);
1613 }
1614
Todd Fiala75f47c32014-10-11 21:42:09 +00001615 //
1616 // This is the parent code here.
1617 //
1618 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1619
Todd Fialaaf245d12014-06-30 21:05:18 +00001620 // Wait for the child process to trap on its call to execve.
1621 ::pid_t wpid;
1622 int status;
1623 if ((wpid = waitpid(pid, &status, 0)) < 0)
1624 {
1625 args->m_error.SetErrorToErrno();
1626
1627 if (log)
1628 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1629
1630 // Mark the inferior as invalid.
1631 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1632 monitor->SetState (StateType::eStateInvalid);
1633
Todd Fiala75f47c32014-10-11 21:42:09 +00001634 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001635 }
1636 else if (WIFEXITED(status))
1637 {
1638 // open, dup or execve likely failed for some reason.
1639 args->m_error.SetErrorToGenericError();
1640 switch (WEXITSTATUS(status))
1641 {
1642 case ePtraceFailed:
1643 args->m_error.SetErrorString("Child ptrace failed.");
1644 break;
1645 case eDupStdinFailed:
1646 args->m_error.SetErrorString("Child open stdin failed.");
1647 break;
1648 case eDupStdoutFailed:
1649 args->m_error.SetErrorString("Child open stdout failed.");
1650 break;
1651 case eDupStderrFailed:
1652 args->m_error.SetErrorString("Child open stderr failed.");
1653 break;
1654 case eChdirFailed:
1655 args->m_error.SetErrorString("Child failed to set working directory.");
1656 break;
1657 case eExecFailed:
1658 args->m_error.SetErrorString("Child exec failed.");
1659 break;
1660 case eSetGidFailed:
1661 args->m_error.SetErrorString("Child setgid failed.");
1662 break;
1663 default:
1664 args->m_error.SetErrorString("Child returned unknown exit status.");
1665 break;
1666 }
1667
1668 if (log)
1669 {
1670 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1671 __FUNCTION__,
1672 WEXITSTATUS(status));
1673 }
1674
1675 // Mark the inferior as invalid.
1676 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1677 monitor->SetState (StateType::eStateInvalid);
1678
Todd Fiala75f47c32014-10-11 21:42:09 +00001679 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001680 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001681 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001682 "Could not sync with inferior process.");
1683
1684 if (log)
1685 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1686
Chaoren Lin97ccc292015-02-03 01:51:12 +00001687 args->m_error = SetDefaultPtraceOpts(pid);
1688 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001689 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001690 if (log)
1691 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1692 __FUNCTION__,
1693 args->m_error.AsCString ());
1694
1695 // Mark the inferior as invalid.
1696 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1697 monitor->SetState (StateType::eStateInvalid);
1698
Todd Fiala75f47c32014-10-11 21:42:09 +00001699 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001700 }
1701
1702 // Release the master terminal descriptor and pass it off to the
1703 // NativeProcessLinux instance. Similarly stash the inferior pid.
1704 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1705 monitor->m_pid = pid;
1706
1707 // Set the terminal fd to be in non blocking mode (it simplifies the
1708 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1709 // descriptor to read from).
1710 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1711 {
1712 if (log)
1713 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1714 __FUNCTION__,
1715 args->m_error.AsCString ());
1716
1717 // Mark the inferior as invalid.
1718 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1719 monitor->SetState (StateType::eStateInvalid);
1720
Todd Fiala75f47c32014-10-11 21:42:09 +00001721 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001722 }
1723
1724 if (log)
1725 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1726
Chaoren Linfa03ad22015-02-03 01:50:42 +00001727 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001728 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001729 monitor->NotifyThreadCreateStopped (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001731
1732 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001733 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001734 monitor->SetState (StateType::eStateStopped);
1735
Todd Fialaaf245d12014-06-30 21:05:18 +00001736 if (log)
1737 {
1738 if (args->m_error.Success ())
1739 {
1740 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1741 }
1742 else
1743 {
1744 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1745 __FUNCTION__,
1746 args->m_error.AsCString ());
1747 }
1748 }
1749 return args->m_error.Success();
1750}
1751
1752void
1753NativeProcessLinux::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1754{
1755 static const char *g_thread_name = "lldb.process.linux.operation";
1756
Zachary Turneracee96a2014-09-23 18:32:09 +00001757 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001758 return;
1759
Zachary Turner39de3112014-09-09 20:54:56 +00001760 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001761}
1762
1763void *
1764NativeProcessLinux::AttachOpThread(void *arg)
1765{
1766 AttachArgs *args = static_cast<AttachArgs*>(arg);
1767
1768 if (!Attach(args)) {
1769 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001770 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 }
1772
1773 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001774 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001775}
1776
1777bool
1778NativeProcessLinux::Attach(AttachArgs *args)
1779{
1780 lldb::pid_t pid = args->m_pid;
1781
1782 NativeProcessLinux *monitor = args->m_monitor;
1783 lldb::ThreadSP inferior;
1784 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1785
1786 // Use a map to keep track of the threads which we have attached/need to attach.
1787 Host::TidMap tids_to_attach;
1788 if (pid <= 1)
1789 {
1790 args->m_error.SetErrorToGenericError();
1791 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1792 goto FINISH;
1793 }
1794
1795 while (Host::FindProcessThreads(pid, tids_to_attach))
1796 {
1797 for (Host::TidMap::iterator it = tids_to_attach.begin();
1798 it != tids_to_attach.end();)
1799 {
1800 if (it->second == false)
1801 {
1802 lldb::tid_t tid = it->first;
1803
1804 // Attach to the requested process.
1805 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001806 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1807 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001808 {
1809 // No such thread. The thread may have exited.
1810 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001811 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001812 {
1813 it = tids_to_attach.erase(it);
1814 continue;
1815 }
1816 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001817 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001818 }
1819
1820 int status;
1821 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1822 // At this point we should have a thread stopped if waitpid succeeds.
1823 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1824 {
1825 // No such thread. The thread may have exited.
1826 // More error handling may be needed.
1827 if (errno == ESRCH)
1828 {
1829 it = tids_to_attach.erase(it);
1830 continue;
1831 }
1832 else
1833 {
1834 args->m_error.SetErrorToErrno();
1835 goto FINISH;
1836 }
1837 }
1838
Chaoren Lin97ccc292015-02-03 01:51:12 +00001839 args->m_error = SetDefaultPtraceOpts(tid);
1840 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001841 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001842
1843
1844 if (log)
1845 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1846
1847 it->second = true;
1848
1849 // Create the thread, mark it as stopped.
1850 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1851 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001852
1853 // This will notify this is a new thread and tell the system it is stopped.
1854 monitor->NotifyThreadCreateStopped (tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001855 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
1856 monitor->SetCurrentThreadID (thread_sp->GetID ());
1857 }
1858
1859 // move the loop forward
1860 ++it;
1861 }
1862 }
1863
1864 if (tids_to_attach.size() > 0)
1865 {
1866 monitor->m_pid = pid;
1867 // Let our process instance know the thread has stopped.
1868 monitor->SetState (StateType::eStateStopped);
1869 }
1870 else
1871 {
1872 args->m_error.SetErrorToGenericError();
1873 args->m_error.SetErrorString("No such process.");
1874 }
1875
1876 FINISH:
1877 return args->m_error.Success();
1878}
1879
Chaoren Lin97ccc292015-02-03 01:51:12 +00001880Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001881NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1882{
1883 long ptrace_opts = 0;
1884
1885 // Have the child raise an event on exit. This is used to keep the child in
1886 // limbo until it is destroyed.
1887 ptrace_opts |= PTRACE_O_TRACEEXIT;
1888
1889 // Have the tracer trace threads which spawn in the inferior process.
1890 // TODO: if we want to support tracing the inferiors' child, add the
1891 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1892 ptrace_opts |= PTRACE_O_TRACECLONE;
1893
1894 // Have the tracer notify us before execve returns
1895 // (needed to disable legacy SIGTRAP generation)
1896 ptrace_opts |= PTRACE_O_TRACEEXEC;
1897
Chaoren Lin97ccc292015-02-03 01:51:12 +00001898 Error error;
1899 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1900 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001901}
1902
1903static ExitType convert_pid_status_to_exit_type (int status)
1904{
1905 if (WIFEXITED (status))
1906 return ExitType::eExitTypeExit;
1907 else if (WIFSIGNALED (status))
1908 return ExitType::eExitTypeSignal;
1909 else if (WIFSTOPPED (status))
1910 return ExitType::eExitTypeStop;
1911 else
1912 {
1913 // We don't know what this is.
1914 return ExitType::eExitTypeInvalid;
1915 }
1916}
1917
1918static int convert_pid_status_to_return_code (int status)
1919{
1920 if (WIFEXITED (status))
1921 return WEXITSTATUS (status);
1922 else if (WIFSIGNALED (status))
1923 return WTERMSIG (status);
1924 else if (WIFSTOPPED (status))
1925 return WSTOPSIG (status);
1926 else
1927 {
1928 // We don't know what this is.
1929 return ExitType::eExitTypeInvalid;
1930 }
1931}
1932
1933// Main process monitoring waitpid-loop handler.
1934bool
1935NativeProcessLinux::MonitorCallback(void *callback_baton,
1936 lldb::pid_t pid,
1937 bool exited,
1938 int signal,
1939 int status)
1940{
1941 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1942
1943 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1944 assert (process && "process is null");
1945 if (!process)
1946 {
1947 if (log)
1948 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1949 return true;
1950 }
1951
1952 // Certain activities differ based on whether the pid is the tid of the main thread.
1953 const bool is_main_thread = (pid == process->GetID ());
1954
1955 // Assume we keep monitoring by default.
1956 bool stop_monitoring = false;
1957
1958 // Handle when the thread exits.
1959 if (exited)
1960 {
1961 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001962 log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
Todd Fialaaf245d12014-06-30 21:05:18 +00001963
1964 // This is a thread that exited. Ensure we're not tracking it anymore.
1965 const bool thread_found = process->StopTrackingThread (pid);
1966
Chaoren Linfa03ad22015-02-03 01:50:42 +00001967 // Make sure the thread state coordinator knows about this.
1968 process->NotifyThreadDeath (pid);
1969
Todd Fialaaf245d12014-06-30 21:05:18 +00001970 if (is_main_thread)
1971 {
1972 // We only set the exit status and notify the delegate if we haven't already set the process
1973 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1974 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001975 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001976 if (!already_notified)
1977 {
1978 if (log)
1979 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (process->GetState ()));
1980 // The main thread exited. We're done monitoring. Report to delegate.
1981 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1982
1983 // Notify delegate that our process has exited.
1984 process->SetState (StateType::eStateExited, true);
1985 }
1986 else
1987 {
1988 if (log)
1989 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1990 }
1991 return true;
1992 }
1993 else
1994 {
1995 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1996 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1997 // and we would have done an all-stop then.
1998 if (log)
1999 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2000
2001 // Not the main thread, we keep going.
2002 return false;
2003 }
2004 }
2005
2006 // Get details on the signal raised.
2007 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002008 const auto err = process->GetSignalInfo(pid, &info);
2009 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002010 {
2011 // We have retrieved the signal info. Dispatch appropriately.
2012 if (info.si_signo == SIGTRAP)
2013 process->MonitorSIGTRAP(&info, pid);
2014 else
2015 process->MonitorSignal(&info, pid, exited);
2016
2017 stop_monitoring = false;
2018 }
2019 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002020 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002021 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002022 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002023 // This is a group stop reception for this tid.
2024 if (log)
2025 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2026 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002027 }
2028 else
2029 {
2030 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2031
2032 // A return value of ESRCH means the thread/process is no longer on the system,
2033 // so it was killed somehow outside of our control. Either way, we can't do anything
2034 // with it anymore.
2035
2036 // We stop monitoring if it was the main thread.
2037 stop_monitoring = is_main_thread;
2038
2039 // Stop tracking the metadata for the thread since it's entirely off the system now.
2040 const bool thread_found = process->StopTrackingThread (pid);
2041
Chaoren Linfa03ad22015-02-03 01:50:42 +00002042 // Make sure the thread state coordinator knows about this.
2043 process->NotifyThreadDeath (pid);
2044
Todd Fialaaf245d12014-06-30 21:05:18 +00002045 if (log)
2046 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002047 __FUNCTION__, err.AsCString(), pid, signal, status, err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +00002048
2049 if (is_main_thread)
2050 {
2051 // Notify the delegate - our process is not available but appears to have been killed outside
2052 // our control. Is eStateExited the right exit state in this case?
2053 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2054 process->SetState (StateType::eStateExited, true);
2055 }
2056 else
2057 {
2058 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2059 if (log)
2060 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, process->GetID (), pid);
2061 }
2062 }
2063 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002064
2065 return stop_monitoring;
2066}
2067
2068void
2069NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2070{
2071 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2072 const bool is_main_thread = (pid == GetID ());
2073
2074 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2075 if (!info)
2076 return;
2077
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002078 Mutex::Locker locker (m_threads_mutex);
2079
Todd Fialaaf245d12014-06-30 21:05:18 +00002080 // See if we can find a thread for this signal.
2081 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2082 if (!thread_sp)
2083 {
2084 if (log)
2085 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2086 }
2087
2088 switch (info->si_code)
2089 {
2090 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2091 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2092 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2093
2094 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2095 {
2096 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2097
Chaoren Linfa03ad22015-02-03 01:50:42 +00002098 // The main thread is stopped here.
2099 if (thread_sp)
2100 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2101 NotifyThreadStop (pid);
2102
Todd Fialaaf245d12014-06-30 21:05:18 +00002103 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002104 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002105 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002106 tid = static_cast<lldb::tid_t> (event_message);
2107 if (log)
2108 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002109
Chaoren Linfa03ad22015-02-03 01:50:42 +00002110 // If we don't track the thread yet: create it, mark as stopped.
2111 // If we do track it, this is the wait we needed. Now resume the new thread.
2112 // In all cases, resume the current (i.e. main process) thread.
2113 bool created_now = false;
2114 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2115 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2116
2117 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2118 if (!created_now)
2119 {
2120 // We can now resume the newly created thread since it is fully created.
2121 NotifyThreadCreateStopped (tid);
2122 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002123 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002124 {
2125 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002126 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002127 },
2128 CoordinatorErrorHandler);
2129 }
2130 else
2131 {
2132 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2133 // this thread is ready to go.
2134 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetLaunching ();
2135 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002136 }
2137 else
2138 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002139 if (log)
2140 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002141 }
2142
2143 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002144 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002145 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002146 {
2147 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002148 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002149 },
2150 CoordinatorErrorHandler);
2151
Todd Fialaaf245d12014-06-30 21:05:18 +00002152 break;
2153 }
2154
2155 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002156 {
2157 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002158 if (log)
2159 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002160
Chaoren Linfa03ad22015-02-03 01:50:42 +00002161 // The thread state coordinator needs to reset due to the exec.
2162 m_coordinator_up->ResetForExec ();
2163
2164 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002165 if (log)
2166 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2167
2168 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002169 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002170 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2171 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002172 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002173 main_thread_sp = thread_sp;
2174 if (log)
2175 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002176 }
2177 else
2178 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002179 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002180 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002181 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002182 }
2183 }
2184
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002185 m_threads.clear ();
2186
2187 if (main_thread_sp)
2188 {
2189 m_threads.push_back (main_thread_sp);
2190 SetCurrentThreadID (main_thread_sp->GetID ());
2191 reinterpret_cast<NativeThreadLinux*>(main_thread_sp.get())->SetStoppedByExec ();
2192 }
2193 else
2194 {
2195 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2196 if (log)
2197 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2198 }
2199
Chaoren Linfa03ad22015-02-03 01:50:42 +00002200 // Tell coordinator about about the "new" (since exec) stopped main thread.
2201 const lldb::tid_t main_thread_tid = GetID ();
2202 NotifyThreadCreateStopped (main_thread_tid);
2203
2204 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2205 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002206 // Let our delegate know we have just exec'd.
2207 NotifyDidExec ();
2208
2209 // If we have a main thread, indicate we are stopped.
2210 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002211
2212 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002213 CallAfterRunningThreadsStop (pid,
2214 [=] (lldb::tid_t signaling_tid)
2215 {
2216 SetState (StateType::eStateStopped, true);
2217 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002218
Todd Fialaaf245d12014-06-30 21:05:18 +00002219 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002220 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002221
2222 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2223 {
2224 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002225
2226 // This thread is currently stopped. It's not actually dead yet, just about to be.
2227 NotifyThreadStop (pid);
2228
Todd Fialaaf245d12014-06-30 21:05:18 +00002229 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002230 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002231 data = -1;
2232
2233 if (log)
2234 {
2235 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2236 __FUNCTION__,
2237 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2238 pid,
2239 is_main_thread ? "is main thread" : "not main thread");
2240 }
2241
Todd Fialaaf245d12014-06-30 21:05:18 +00002242 if (is_main_thread)
2243 {
2244 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002245 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002246
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002247 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002248 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002249 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002250 {
2251 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002252 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002253 },
2254 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002255
2256 break;
2257 }
2258
2259 case 0:
2260 case TRAP_TRACE:
2261 // We receive this on single stepping.
2262 if (log)
2263 log->Printf ("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", __FUNCTION__, pid);
2264
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002265 if (thread_sp)
2266 {
Chaoren Lin28e57422015-02-03 01:51:25 +00002267 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByTrace ();
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002268 }
2269
Chaoren Linfa03ad22015-02-03 01:50:42 +00002270 // This thread is currently stopped.
2271 NotifyThreadStop (pid);
2272
Chaoren Linae29d392015-02-03 01:50:46 +00002273 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2274 // This would have already happened at the time the Resume() with step operation was signaled.
2275 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2276 // once all running threads have checked in as stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002277 SetCurrentThreadID (pid);
2278 // Tell the process we have a stop (from software breakpoint).
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002279 CallAfterRunningThreadsStop (pid,
2280 [=] (lldb::tid_t signaling_tid)
2281 {
2282 SetState (StateType::eStateStopped, true);
2283 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002284 break;
2285
2286 case SI_KERNEL:
2287 case TRAP_BRKPT:
2288 if (log)
2289 log->Printf ("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2290
Chaoren Linfa03ad22015-02-03 01:50:42 +00002291 // This thread is currently stopped.
2292 NotifyThreadStop (pid);
2293
Todd Fialaaf245d12014-06-30 21:05:18 +00002294 // Mark the thread as stopped at breakpoint.
2295 if (thread_sp)
2296 {
Chaoren Lin28e57422015-02-03 01:51:25 +00002297 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByBreakpoint ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002298 Error error = FixupBreakpointPCAsNeeded (thread_sp);
2299 if (error.Fail ())
2300 {
2301 if (log)
2302 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", __FUNCTION__, pid, error.AsCString ());
2303 }
2304 }
2305 else
2306 {
2307 if (log)
2308 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": warning, cannot process software breakpoint since no thread metadata", __FUNCTION__, pid);
2309 }
2310
2311
Chaoren Linfa03ad22015-02-03 01:50:42 +00002312 // We need to tell all other running threads before we notify the delegate about this stop.
2313 CallAfterRunningThreadsStop (pid,
2314 [=](lldb::tid_t deferred_notification_tid)
2315 {
2316 SetCurrentThreadID (deferred_notification_tid);
2317 // Tell the process we have a stop (from software breakpoint).
2318 SetState (StateType::eStateStopped, true);
2319 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002320 break;
2321
2322 case TRAP_HWBKPT:
2323 if (log)
2324 log->Printf ("NativeProcessLinux::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2325
Chaoren Linfa03ad22015-02-03 01:50:42 +00002326 // This thread is currently stopped.
2327 NotifyThreadStop (pid);
2328
Todd Fialaaf245d12014-06-30 21:05:18 +00002329 // Mark the thread as stopped at watchpoint.
2330 // The address is at (lldb::addr_t)info->si_addr if we need it.
2331 if (thread_sp)
Chaoren Lin18fe6402015-02-03 01:51:47 +00002332 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByWatchpoint ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002333 else
2334 {
2335 if (log)
2336 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ": warning, cannot process hardware breakpoint since no thread metadata", __FUNCTION__, GetID (), pid);
2337 }
2338
Chaoren Linfa03ad22015-02-03 01:50:42 +00002339 // We need to tell all other running threads before we notify the delegate about this stop.
2340 CallAfterRunningThreadsStop (pid,
2341 [=](lldb::tid_t deferred_notification_tid)
2342 {
2343 SetCurrentThreadID (deferred_notification_tid);
2344 // Tell the process we have a stop (from hardware breakpoint).
2345 SetState (StateType::eStateStopped, true);
2346 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002347 break;
2348
2349 case SIGTRAP:
2350 case (SIGTRAP | 0x80):
2351 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002352 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2353
2354 // This thread is currently stopped.
2355 NotifyThreadStop (pid);
2356 if (thread_sp)
2357 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2358
2359
Todd Fialaaf245d12014-06-30 21:05:18 +00002360 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002361 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002362 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002363 {
2364 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002365 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002366 },
2367 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002368 break;
2369
2370 default:
2371 assert(false && "Unexpected SIGTRAP code!");
2372 if (log)
2373 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%" PRIx64, __FUNCTION__, GetID (), pid, static_cast<uint64_t> (SIGTRAP | (PTRACE_EVENT_CLONE << 8)));
2374 break;
2375
2376 }
2377}
2378
2379void
2380NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2381{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002382 assert (info && "null info");
2383 if (!info)
2384 return;
2385
2386 const int signo = info->si_signo;
2387 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002388
2389 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2390
2391 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2392 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2393 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2394 //
2395 // IOW, user generated signals never generate what we consider to be a
2396 // "crash".
2397 //
2398 // Similarly, ACK signals generated by this monitor.
2399
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002400 Mutex::Locker locker (m_threads_mutex);
2401
Todd Fialaaf245d12014-06-30 21:05:18 +00002402 // See if we can find a thread for this signal.
2403 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2404 if (!thread_sp)
2405 {
2406 if (log)
2407 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2408 }
2409
2410 // Handle the signal.
2411 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2412 {
2413 if (log)
2414 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2415 __FUNCTION__,
2416 GetUnixSignals ().GetSignalAsCString (signo),
2417 signo,
2418 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2419 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002420 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002421 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002422 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002423
Todd Fiala58a2f662014-08-12 17:02:07 +00002424 // Check for new thread notification.
2425 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2426 {
2427 // A new thread creation is being signaled. This is one of two parts that come in
2428 // a non-deterministic order. pid is the thread id.
2429 if (log)
2430 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2431 __FUNCTION__, GetID (), pid);
2432
2433 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002434 bool created_now = false;
2435 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002436 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2437
2438 // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002439 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002440 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002441 // We can now resume the newly created thread since it is fully created.
2442 NotifyThreadCreateStopped (pid);
2443 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002444 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002445 {
2446 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002447 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002448 },
2449 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002450 }
2451 else
2452 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002453 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2454 // this thread is ready to go.
2455 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002456 }
2457
Todd Fiala58a2f662014-08-12 17:02:07 +00002458 // Done handling.
2459 return;
2460 }
2461
2462 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002463 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002464 {
2465 // This is a tgkill()-based stop.
2466 if (thread_sp)
2467 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002468 if (log)
2469 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2470 __FUNCTION__,
2471 GetID (),
2472 pid);
2473
Chaoren Linaab58632015-02-03 01:50:57 +00002474 // Check that we're not already marked with a stop reason.
2475 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2476 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2477 // and that, without an intervening resume, we received another stop. It is more likely
2478 // that we are missing the marking of a run state somewhere if we find that the thread was
2479 // marked as stopped.
2480 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ());
2481 assert (linux_thread_p && "linux_thread_p is null!");
2482
2483 const StateType thread_state = linux_thread_p->GetState ();
2484 if (!StateIsStoppedState (thread_state, false))
2485 {
2486 // An inferior thread just stopped, but was not the primary cause of the process stop.
2487 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2488 // stop signal as 0 to let lldb know this isn't the important stop.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002489 linux_thread_p->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002490 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002491 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002492 }
2493 else
2494 {
2495 if (log)
2496 {
2497 // Retrieve the signal name if the thread was stopped by a signal.
2498 int stop_signo = 0;
2499 const bool stopped_by_signal = linux_thread_p->IsStopped (&stop_signo);
2500 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2501 if (!signal_name)
2502 signal_name = "<no-signal-name>";
2503
2504 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is",
2505 __FUNCTION__,
2506 GetID (),
2507 linux_thread_p->GetID (),
2508 StateAsCString (thread_state),
2509 stop_signo,
2510 signal_name);
2511 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002512 // Tell the thread state coordinator about the stop.
2513 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002514 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002515 }
2516
2517 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002518 return;
2519 }
2520
2521 if (log)
2522 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2523
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002524 // This thread is stopped.
2525 NotifyThreadStop (pid);
2526
Todd Fialaaf245d12014-06-30 21:05:18 +00002527 switch (signo)
2528 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002529 case SIGSTOP:
2530 {
2531 if (log)
2532 {
2533 if (is_from_llgs)
2534 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2535 else
2536 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2537 }
2538
Chaoren Linfa03ad22015-02-03 01:50:42 +00002539 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2540 // This thread will get stopped again as part of the group-stop completion.
2541 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002542 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002543 {
2544 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2545 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002546 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002547 },
2548 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002549 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002550 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002551 case SIGSEGV:
2552 case SIGILL:
2553 case SIGFPE:
2554 case SIGBUS:
2555 if (thread_sp)
Chaoren Lin28e57422015-02-03 01:51:25 +00002556 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002557 break;
2558 default:
2559 // This is just a pre-signal-delivery notification of the incoming signal.
2560 if (thread_sp)
2561 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2562
2563 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002564 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002565
2566 // Send a stop to the debugger after we get all other threads to stop.
2567 CallAfterRunningThreadsStop (pid,
2568 [=] (lldb::tid_t signaling_tid)
2569 {
2570 SetCurrentThreadID (signaling_tid);
2571 SetState (StateType::eStateStopped, true);
2572 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002573}
2574
2575Error
2576NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2577{
Todd Fialaaf245d12014-06-30 21:05:18 +00002578 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2579 if (log)
2580 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2581
Chaoren Lin03f12d62015-02-03 01:50:49 +00002582 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2583 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002584 int deferred_signo = 0;
2585 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002586 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002587
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002588 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002589
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002590 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002591 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002592 assert (thread_sp && "thread list should not contain NULL threads");
2593
2594 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2595
2596 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002597 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002598 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002599 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2600 __FUNCTION__, GetID (), thread_sp->GetID ());
2601 continue;
2602 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002603
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002604 if (log)
2605 {
2606 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2607 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2608 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002609
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002610 switch (action->state)
2611 {
2612 case eStateRunning:
2613 {
2614 // Run the thread, possibly feeding it the signal.
2615 const int signo = action->signal;
2616 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2617 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2618 {
2619 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2620 // Pass this signal number on to the inferior to handle.
2621 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2622 if (resume_result.Success())
2623 SetState(eStateRunning, true);
2624 return resume_result;
2625 },
2626 CoordinatorErrorHandler);
2627 break;
2628 }
2629
2630 case eStateStepping:
2631 {
2632 // Request the step.
2633 const int signo = action->signal;
2634 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2635 [=](lldb::tid_t tid_to_step, bool supress_signal)
2636 {
2637 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStepping ();
2638 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2639 assert (step_result.Success() && "SingleStep() failed");
2640 if (step_result.Success())
2641 SetState(eStateStepping, true);
2642 return step_result;
2643 },
2644 CoordinatorErrorHandler);
2645 stepping = true;
2646 break;
2647 }
2648
2649 case eStateSuspended:
2650 case eStateStopped:
2651 // if we haven't chosen a deferred signal tid yet, use this one.
2652 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002653 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002654 deferred_signal_tid = thread_sp->GetID ();
2655 deferred_signal_thread_sp = thread_sp;
2656 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002657 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002658 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002659
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002660 default:
2661 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2662 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002663 }
2664 }
2665
Chaoren Linfa03ad22015-02-03 01:50:42 +00002666 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2667 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002668 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2669 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002670 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002671 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2672 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002673 [=](lldb::tid_t deferred_notification_tid)
2674 {
Chaoren Linae29d392015-02-03 01:50:46 +00002675 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002676 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002677
2678 // Set the thread state as stopped by the deferred signo.
2679 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (deferred_signo);
2680
2681 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002682 SetState (StateType::eStateStopped, true);
2683 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002684 }
2685
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002686 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002687}
2688
2689Error
2690NativeProcessLinux::Halt ()
2691{
2692 Error error;
2693
Todd Fialaaf245d12014-06-30 21:05:18 +00002694 if (kill (GetID (), SIGSTOP) != 0)
2695 error.SetErrorToErrno ();
2696
2697 return error;
2698}
2699
2700Error
2701NativeProcessLinux::Detach ()
2702{
2703 Error error;
2704
2705 // Tell ptrace to detach from the process.
2706 if (GetID () != LLDB_INVALID_PROCESS_ID)
2707 error = Detach (GetID ());
2708
2709 // Stop monitoring the inferior.
2710 StopMonitor ();
2711
2712 // No error.
2713 return error;
2714}
2715
2716Error
2717NativeProcessLinux::Signal (int signo)
2718{
2719 Error error;
2720
2721 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2722 if (log)
2723 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2724 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2725
2726 if (kill(GetID(), signo))
2727 error.SetErrorToErrno();
2728
2729 return error;
2730}
2731
2732Error
Chaoren Line9547b82015-02-03 01:51:00 +00002733NativeProcessLinux::Interrupt ()
2734{
2735 // Pick a running thread (or if none, a not-dead stopped thread) as
2736 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002737 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2738
2739 NativeThreadProtocolSP running_thread_sp;
2740 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002741
2742 if (log)
2743 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2744
2745 Mutex::Locker locker (m_threads_mutex);
2746
2747 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002748 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002749 // The thread shouldn't be null but lets just cover that here.
2750 if (!thread_sp)
2751 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002752
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002753 // If we have a running or stepping thread, we'll call that the
2754 // target of the interrupt.
2755 const auto thread_state = thread_sp->GetState ();
2756 if (thread_state == eStateRunning ||
2757 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002758 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002759 running_thread_sp = thread_sp;
2760 break;
2761 }
2762 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2763 {
2764 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2765 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002766 }
2767 }
2768
2769 if (!running_thread_sp && !stopped_thread_sp)
2770 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002771 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002772 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002773 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002774
Chaoren Line9547b82015-02-03 01:51:00 +00002775 return error;
2776 }
2777
2778 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2779
2780 if (log)
2781 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2782 __FUNCTION__,
2783 GetID (),
2784 running_thread_sp ? "running" : "stopped",
2785 deferred_signal_thread_sp->GetID ());
2786
2787 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2788 [=](lldb::tid_t deferred_notification_tid)
2789 {
2790 // Set the signal thread to the current thread.
2791 SetCurrentThreadID (deferred_notification_tid);
2792
2793 // Set the thread state as stopped by the deferred signo.
2794 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
2795
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002796 // Tell the process delegate that the process is in a stopped state.
2797 SetState (StateType::eStateStopped, true);
2798 });
2799 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002800}
2801
2802Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002803NativeProcessLinux::Kill ()
2804{
2805 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2806 if (log)
2807 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2808
2809 Error error;
2810
2811 switch (m_state)
2812 {
2813 case StateType::eStateInvalid:
2814 case StateType::eStateExited:
2815 case StateType::eStateCrashed:
2816 case StateType::eStateDetached:
2817 case StateType::eStateUnloaded:
2818 // Nothing to do - the process is already dead.
2819 if (log)
2820 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2821 return error;
2822
2823 case StateType::eStateConnected:
2824 case StateType::eStateAttaching:
2825 case StateType::eStateLaunching:
2826 case StateType::eStateStopped:
2827 case StateType::eStateRunning:
2828 case StateType::eStateStepping:
2829 case StateType::eStateSuspended:
2830 // We can try to kill a process in these states.
2831 break;
2832 }
2833
2834 if (kill (GetID (), SIGKILL) != 0)
2835 {
2836 error.SetErrorToErrno ();
2837 return error;
2838 }
2839
2840 return error;
2841}
2842
2843static Error
2844ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2845{
2846 memory_region_info.Clear();
2847
2848 StringExtractor line_extractor (maps_line.c_str ());
2849
2850 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2851 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2852
2853 // Parse out the starting address
2854 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2855
2856 // Parse out hyphen separating start and end address from range.
2857 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2858 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2859
2860 // Parse out the ending address
2861 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2862
2863 // Parse out the space after the address.
2864 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2865 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2866
2867 // Save the range.
2868 memory_region_info.GetRange ().SetRangeBase (start_address);
2869 memory_region_info.GetRange ().SetRangeEnd (end_address);
2870
2871 // Parse out each permission entry.
2872 if (line_extractor.GetBytesLeft () < 4)
2873 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2874
2875 // Handle read permission.
2876 const char read_perm_char = line_extractor.GetChar ();
2877 if (read_perm_char == 'r')
2878 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2879 else
2880 {
2881 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2882 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2883 }
2884
2885 // Handle write permission.
2886 const char write_perm_char = line_extractor.GetChar ();
2887 if (write_perm_char == 'w')
2888 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2889 else
2890 {
2891 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2892 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2893 }
2894
2895 // Handle execute permission.
2896 const char exec_perm_char = line_extractor.GetChar ();
2897 if (exec_perm_char == 'x')
2898 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2899 else
2900 {
2901 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2902 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2903 }
2904
2905 return Error ();
2906}
2907
2908Error
2909NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2910{
2911 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2912 // with no perms if it is not mapped.
2913
2914 // Use an approach that reads memory regions from /proc/{pid}/maps.
2915 // Assume proc maps entries are in ascending order.
2916 // FIXME assert if we find differently.
2917 Mutex::Locker locker (m_mem_region_cache_mutex);
2918
2919 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2920 Error error;
2921
2922 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2923 {
2924 // We're done.
2925 error.SetErrorString ("unsupported");
2926 return error;
2927 }
2928
2929 // If our cache is empty, pull the latest. There should always be at least one memory region
2930 // if memory region handling is supported.
2931 if (m_mem_region_cache.empty ())
2932 {
2933 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2934 [&] (const std::string &line) -> bool
2935 {
2936 MemoryRegionInfo info;
2937 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2938 if (parse_error.Success ())
2939 {
2940 m_mem_region_cache.push_back (info);
2941 return true;
2942 }
2943 else
2944 {
2945 if (log)
2946 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2947 return false;
2948 }
2949 });
2950
2951 // If we had an error, we'll mark unsupported.
2952 if (error.Fail ())
2953 {
2954 m_supports_mem_region = LazyBool::eLazyBoolNo;
2955 return error;
2956 }
2957 else if (m_mem_region_cache.empty ())
2958 {
2959 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2960 // is supported. Assume we don't support map entries via procfs.
2961 if (log)
2962 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2963 m_supports_mem_region = LazyBool::eLazyBoolNo;
2964 error.SetErrorString ("not supported");
2965 return error;
2966 }
2967
2968 if (log)
2969 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2970
2971 // We support memory retrieval, remember that.
2972 m_supports_mem_region = LazyBool::eLazyBoolYes;
2973 }
2974 else
2975 {
2976 if (log)
2977 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2978 }
2979
2980 lldb::addr_t prev_base_address = 0;
2981
2982 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2983 // There can be a ton of regions on pthreads apps with lots of threads.
2984 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2985 {
2986 MemoryRegionInfo &proc_entry_info = *it;
2987
2988 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2989 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2990 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2991
2992 // If the target address comes before this entry, indicate distance to next region.
2993 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2994 {
2995 range_info.GetRange ().SetRangeBase (load_addr);
2996 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2997 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2998 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2999 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3000
3001 return error;
3002 }
3003 else if (proc_entry_info.GetRange ().Contains (load_addr))
3004 {
3005 // The target address is within the memory region we're processing here.
3006 range_info = proc_entry_info;
3007 return error;
3008 }
3009
3010 // The target memory address comes somewhere after the region we just parsed.
3011 }
3012
3013 // If we made it here, we didn't find an entry that contained the given address.
3014 error.SetErrorString ("address comes after final region");
3015
3016 if (log)
3017 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3018
3019 return error;
3020}
3021
3022void
3023NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3024{
3025 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3026 if (log)
3027 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3028
3029 {
3030 Mutex::Locker locker (m_mem_region_cache_mutex);
3031 if (log)
3032 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3033 m_mem_region_cache.clear ();
3034 }
3035}
3036
3037Error
3038NativeProcessLinux::AllocateMemory (
3039 lldb::addr_t size,
3040 uint32_t permissions,
3041 lldb::addr_t &addr)
3042{
3043 // FIXME implementing this requires the equivalent of
3044 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3045 // functional ThreadPlans working with Native*Protocol.
3046#if 1
3047 return Error ("not implemented yet");
3048#else
3049 addr = LLDB_INVALID_ADDRESS;
3050
3051 unsigned prot = 0;
3052 if (permissions & lldb::ePermissionsReadable)
3053 prot |= eMmapProtRead;
3054 if (permissions & lldb::ePermissionsWritable)
3055 prot |= eMmapProtWrite;
3056 if (permissions & lldb::ePermissionsExecutable)
3057 prot |= eMmapProtExec;
3058
3059 // TODO implement this directly in NativeProcessLinux
3060 // (and lift to NativeProcessPOSIX if/when that class is
3061 // refactored out).
3062 if (InferiorCallMmap(this, addr, 0, size, prot,
3063 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3064 m_addr_to_mmap_size[addr] = size;
3065 return Error ();
3066 } else {
3067 addr = LLDB_INVALID_ADDRESS;
3068 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3069 }
3070#endif
3071}
3072
3073Error
3074NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3075{
3076 // FIXME see comments in AllocateMemory - required lower-level
3077 // bits not in place yet (ThreadPlans)
3078 return Error ("not implemented");
3079}
3080
3081lldb::addr_t
3082NativeProcessLinux::GetSharedLibraryInfoAddress ()
3083{
3084#if 1
3085 // punt on this for now
3086 return LLDB_INVALID_ADDRESS;
3087#else
3088 // Return the image info address for the exe module
3089#if 1
3090 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3091
3092 ModuleSP module_sp;
3093 Error error = GetExeModuleSP (module_sp);
3094 if (error.Fail ())
3095 {
3096 if (log)
3097 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3098 return LLDB_INVALID_ADDRESS;
3099 }
3100
3101 if (module_sp == nullptr)
3102 {
3103 if (log)
3104 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3105 return LLDB_INVALID_ADDRESS;
3106 }
3107
3108 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3109 if (object_file_sp == nullptr)
3110 {
3111 if (log)
3112 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3113 return LLDB_INVALID_ADDRESS;
3114 }
3115
3116 return obj_file_sp->GetImageInfoAddress();
3117#else
3118 Target *target = &GetTarget();
3119 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3120 Address addr = obj_file->GetImageInfoAddress(target);
3121
3122 if (addr.IsValid())
3123 return addr.GetLoadAddress(target);
3124 return LLDB_INVALID_ADDRESS;
3125#endif
3126#endif // punt on this for now
3127}
3128
3129size_t
3130NativeProcessLinux::UpdateThreads ()
3131{
3132 // The NativeProcessLinux monitoring threads are always up to date
3133 // with respect to thread state and they keep the thread list
3134 // populated properly. All this method needs to do is return the
3135 // thread count.
3136 Mutex::Locker locker (m_threads_mutex);
3137 return m_threads.size ();
3138}
3139
3140bool
3141NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3142{
3143 arch = m_arch;
3144 return true;
3145}
3146
3147Error
3148NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3149{
3150 // FIXME put this behind a breakpoint protocol class that can be
3151 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003152 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003153 static const uint8_t g_i386_opcode [] = { 0xCC };
3154
3155 switch (m_arch.GetMachine ())
3156 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003157 case llvm::Triple::aarch64:
3158 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3159 return Error ();
3160
Todd Fialaaf245d12014-06-30 21:05:18 +00003161 case llvm::Triple::x86:
3162 case llvm::Triple::x86_64:
3163 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3164 return Error ();
3165
3166 default:
3167 assert(false && "CPU type not supported!");
3168 return Error ("CPU type not supported");
3169 }
3170}
3171
3172Error
3173NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3174{
3175 if (hardware)
3176 return Error ("NativeProcessLinux does not support hardware breakpoints");
3177 else
3178 return SetSoftwareBreakpoint (addr, size);
3179}
3180
3181Error
3182NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3183{
3184 // FIXME put this behind a breakpoint protocol class that can be
3185 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003186 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003187 static const uint8_t g_i386_opcode [] = { 0xCC };
3188
3189 switch (m_arch.GetMachine ())
3190 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003191 case llvm::Triple::aarch64:
3192 trap_opcode_bytes = g_aarch64_opcode;
3193 actual_opcode_size = sizeof(g_aarch64_opcode);
3194 return Error ();
3195
Todd Fialaaf245d12014-06-30 21:05:18 +00003196 case llvm::Triple::x86:
3197 case llvm::Triple::x86_64:
3198 trap_opcode_bytes = g_i386_opcode;
3199 actual_opcode_size = sizeof(g_i386_opcode);
3200 return Error ();
3201
3202 default:
3203 assert(false && "CPU type not supported!");
3204 return Error ("CPU type not supported");
3205 }
3206}
3207
3208#if 0
3209ProcessMessage::CrashReason
3210NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3211{
3212 ProcessMessage::CrashReason reason;
3213 assert(info->si_signo == SIGSEGV);
3214
3215 reason = ProcessMessage::eInvalidCrashReason;
3216
3217 switch (info->si_code)
3218 {
3219 default:
3220 assert(false && "unexpected si_code for SIGSEGV");
3221 break;
3222 case SI_KERNEL:
3223 // Linux will occasionally send spurious SI_KERNEL codes.
3224 // (this is poorly documented in sigaction)
3225 // One way to get this is via unaligned SIMD loads.
3226 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3227 break;
3228 case SEGV_MAPERR:
3229 reason = ProcessMessage::eInvalidAddress;
3230 break;
3231 case SEGV_ACCERR:
3232 reason = ProcessMessage::ePrivilegedAddress;
3233 break;
3234 }
3235
3236 return reason;
3237}
3238#endif
3239
3240
3241#if 0
3242ProcessMessage::CrashReason
3243NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3244{
3245 ProcessMessage::CrashReason reason;
3246 assert(info->si_signo == SIGILL);
3247
3248 reason = ProcessMessage::eInvalidCrashReason;
3249
3250 switch (info->si_code)
3251 {
3252 default:
3253 assert(false && "unexpected si_code for SIGILL");
3254 break;
3255 case ILL_ILLOPC:
3256 reason = ProcessMessage::eIllegalOpcode;
3257 break;
3258 case ILL_ILLOPN:
3259 reason = ProcessMessage::eIllegalOperand;
3260 break;
3261 case ILL_ILLADR:
3262 reason = ProcessMessage::eIllegalAddressingMode;
3263 break;
3264 case ILL_ILLTRP:
3265 reason = ProcessMessage::eIllegalTrap;
3266 break;
3267 case ILL_PRVOPC:
3268 reason = ProcessMessage::ePrivilegedOpcode;
3269 break;
3270 case ILL_PRVREG:
3271 reason = ProcessMessage::ePrivilegedRegister;
3272 break;
3273 case ILL_COPROC:
3274 reason = ProcessMessage::eCoprocessorError;
3275 break;
3276 case ILL_BADSTK:
3277 reason = ProcessMessage::eInternalStackError;
3278 break;
3279 }
3280
3281 return reason;
3282}
3283#endif
3284
3285#if 0
3286ProcessMessage::CrashReason
3287NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3288{
3289 ProcessMessage::CrashReason reason;
3290 assert(info->si_signo == SIGFPE);
3291
3292 reason = ProcessMessage::eInvalidCrashReason;
3293
3294 switch (info->si_code)
3295 {
3296 default:
3297 assert(false && "unexpected si_code for SIGFPE");
3298 break;
3299 case FPE_INTDIV:
3300 reason = ProcessMessage::eIntegerDivideByZero;
3301 break;
3302 case FPE_INTOVF:
3303 reason = ProcessMessage::eIntegerOverflow;
3304 break;
3305 case FPE_FLTDIV:
3306 reason = ProcessMessage::eFloatDivideByZero;
3307 break;
3308 case FPE_FLTOVF:
3309 reason = ProcessMessage::eFloatOverflow;
3310 break;
3311 case FPE_FLTUND:
3312 reason = ProcessMessage::eFloatUnderflow;
3313 break;
3314 case FPE_FLTRES:
3315 reason = ProcessMessage::eFloatInexactResult;
3316 break;
3317 case FPE_FLTINV:
3318 reason = ProcessMessage::eFloatInvalidOperation;
3319 break;
3320 case FPE_FLTSUB:
3321 reason = ProcessMessage::eFloatSubscriptRange;
3322 break;
3323 }
3324
3325 return reason;
3326}
3327#endif
3328
3329#if 0
3330ProcessMessage::CrashReason
3331NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3332{
3333 ProcessMessage::CrashReason reason;
3334 assert(info->si_signo == SIGBUS);
3335
3336 reason = ProcessMessage::eInvalidCrashReason;
3337
3338 switch (info->si_code)
3339 {
3340 default:
3341 assert(false && "unexpected si_code for SIGBUS");
3342 break;
3343 case BUS_ADRALN:
3344 reason = ProcessMessage::eIllegalAlignment;
3345 break;
3346 case BUS_ADRERR:
3347 reason = ProcessMessage::eIllegalAddress;
3348 break;
3349 case BUS_OBJERR:
3350 reason = ProcessMessage::eHardwareError;
3351 break;
3352 }
3353
3354 return reason;
3355}
3356#endif
3357
3358void
3359NativeProcessLinux::ServeOperation(OperationArgs *args)
3360{
3361 NativeProcessLinux *monitor = args->m_monitor;
3362
3363 // We are finised with the arguments and are ready to go. Sync with the
3364 // parent thread and start serving operations on the inferior.
3365 sem_post(&args->m_semaphore);
3366
3367 for(;;)
3368 {
3369 // wait for next pending operation
3370 if (sem_wait(&monitor->m_operation_pending))
3371 {
3372 if (errno == EINTR)
3373 continue;
3374 assert(false && "Unexpected errno from sem_wait");
3375 }
3376
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003377 // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3378 // android. We don't have to send a post to the m_operation_done semaphore because in this
3379 // case the synchronization is achieved by a Join() call
3380 if (monitor->m_operation == EXIT_OPERATION)
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003381 break;
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003382
Todd Fialaaf245d12014-06-30 21:05:18 +00003383 reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3384
3385 // notify calling thread that operation is complete
3386 sem_post(&monitor->m_operation_done);
3387 }
3388}
3389
3390void
3391NativeProcessLinux::DoOperation(void *op)
3392{
3393 Mutex::Locker lock(m_operation_mutex);
3394
3395 m_operation = op;
3396
3397 // notify operation thread that an operation is ready to be processed
3398 sem_post(&m_operation_pending);
3399
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003400 // Don't wait for the operation to complete in case of an exit operation. The operation thread
3401 // will exit without posting to the semaphore
3402 if (m_operation == EXIT_OPERATION)
3403 return;
3404
Todd Fialaaf245d12014-06-30 21:05:18 +00003405 // wait for operation to complete
3406 while (sem_wait(&m_operation_done))
3407 {
3408 if (errno == EINTR)
3409 continue;
3410 assert(false && "Unexpected errno from sem_wait");
3411 }
3412}
3413
3414Error
3415NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3416{
3417 ReadOperation op(addr, buf, size, bytes_read);
3418 DoOperation(&op);
3419 return op.GetError ();
3420}
3421
3422Error
3423NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3424{
3425 WriteOperation op(addr, buf, size, bytes_written);
3426 DoOperation(&op);
3427 return op.GetError ();
3428}
3429
Chaoren Lin97ccc292015-02-03 01:51:12 +00003430Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003431NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3432 uint32_t size, RegisterValue &value)
3433{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003434 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003435 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003436 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003437}
3438
Chaoren Lin97ccc292015-02-03 01:51:12 +00003439Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003440NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3441 const char* reg_name, const RegisterValue &value)
3442{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003443 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003444 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003445 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003446}
3447
Chaoren Lin97ccc292015-02-03 01:51:12 +00003448Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003449NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3450{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003451 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003452 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003453 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003454}
3455
Chaoren Lin97ccc292015-02-03 01:51:12 +00003456Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003457NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3458{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003459 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003460 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003461 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003462}
3463
Chaoren Lin97ccc292015-02-03 01:51:12 +00003464Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003465NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3466{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003467 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003468 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003469 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003470}
3471
Chaoren Lin97ccc292015-02-03 01:51:12 +00003472Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003473NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3474{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003475 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003476 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003477 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003478}
3479
Chaoren Lin97ccc292015-02-03 01:51:12 +00003480Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003481NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3482{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003483 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003484 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003485 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003486}
3487
Chaoren Lin97ccc292015-02-03 01:51:12 +00003488Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003489NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3490{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003491 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003492 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003493 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003494}
3495
Chaoren Lin97ccc292015-02-03 01:51:12 +00003496Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003497NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3498{
Todd Fialaaf245d12014-06-30 21:05:18 +00003499 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3500
3501 if (log)
3502 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3503 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003504 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003505 DoOperation (&op);
3506 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003507 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3508 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003509}
3510
Chaoren Lin97ccc292015-02-03 01:51:12 +00003511Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003512NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3513{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003514 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003515 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003516 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003517}
3518
Chaoren Lin97ccc292015-02-03 01:51:12 +00003519Error
3520NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003521{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003522 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003523 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003524 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003525}
3526
Chaoren Lin97ccc292015-02-03 01:51:12 +00003527Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003528NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3529{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003530 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003531 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003532 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003533}
3534
3535lldb_private::Error
3536NativeProcessLinux::Detach(lldb::tid_t tid)
3537{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003538 if (tid == LLDB_INVALID_THREAD_ID)
3539 return Error();
3540
3541 DetachOperation op(tid);
3542 DoOperation(&op);
3543 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003544}
3545
3546bool
3547NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3548{
3549 int target_fd = open(path, flags, 0666);
3550
3551 if (target_fd == -1)
3552 return false;
3553
Pavel Labath493c3a12015-02-04 10:36:57 +00003554 if (dup2(target_fd, fd) == -1)
3555 return false;
3556
3557 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003558}
3559
3560void
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003561NativeProcessLinux::StopMonitorThread()
Todd Fialaaf245d12014-06-30 21:05:18 +00003562{
Zachary Turneracee96a2014-09-23 18:32:09 +00003563 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003564 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003565 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00003566 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003567 }
3568}
3569
3570void
3571NativeProcessLinux::StopMonitor()
3572{
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003573 StopMonitorThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003574 StopCoordinatorThread ();
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003575 StopOpThread();
Todd Fialaaf245d12014-06-30 21:05:18 +00003576 sem_destroy(&m_operation_pending);
3577 sem_destroy(&m_operation_done);
3578
3579 // TODO: validate whether this still holds, fix up comment.
3580 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3581 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3582 // the descriptor to a ConnectionFileDescriptor object. Consequently
3583 // even though still has the file descriptor, we shouldn't close it here.
3584}
3585
3586void
3587NativeProcessLinux::StopOpThread()
3588{
Zachary Turneracee96a2014-09-23 18:32:09 +00003589 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003590 return;
3591
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003592 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00003593 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003594}
3595
Chaoren Linfa03ad22015-02-03 01:50:42 +00003596Error
3597NativeProcessLinux::StartCoordinatorThread ()
3598{
3599 Error error;
3600 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3601 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3602
3603 // Skip if thread is already running
3604 if (m_coordinator_thread.IsJoinable())
3605 {
3606 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3607 if (log)
3608 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3609 return error;
3610 }
3611
3612 // Enable verbose logging if lldb thread logging is enabled.
3613 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3614
3615 if (log)
3616 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3617 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3618 return error;
3619}
3620
3621void *
3622NativeProcessLinux::CoordinatorThread (void *arg)
3623{
3624 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3625
3626 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3627 assert (process && "null process passed to CoordinatorThread");
3628 if (!process)
3629 {
3630 if (log)
3631 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3632 return nullptr;
3633 }
3634
3635 // Run the thread state coordinator loop until it is done. This call uses
3636 // efficient waiting for an event to be ready.
3637 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3638 {
3639 }
3640
3641 if (log)
3642 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3643
3644 return nullptr;
3645}
3646
3647void
3648NativeProcessLinux::StopCoordinatorThread()
3649{
3650 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3651 if (log)
3652 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3653
3654 // Tell the coordinator we're done. This will cause the coordinator
3655 // run loop thread to exit when the processing queue hits this message.
3656 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003657 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003658}
3659
Todd Fialaaf245d12014-06-30 21:05:18 +00003660bool
3661NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3662{
3663 for (auto thread_sp : m_threads)
3664 {
3665 assert (thread_sp && "thread list should not contain NULL threads");
3666 if (thread_sp->GetID () == thread_id)
3667 {
3668 // We have this thread.
3669 return true;
3670 }
3671 }
3672
3673 // We don't have this thread.
3674 return false;
3675}
3676
3677NativeThreadProtocolSP
3678NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3679{
3680 // CONSIDER organize threads by map - we can do better than linear.
3681 for (auto thread_sp : m_threads)
3682 {
3683 if (thread_sp->GetID () == thread_id)
3684 return thread_sp;
3685 }
3686
3687 // We don't have this thread.
3688 return NativeThreadProtocolSP ();
3689}
3690
3691bool
3692NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3693{
3694 Mutex::Locker locker (m_threads_mutex);
3695 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3696 {
3697 if (*it && ((*it)->GetID () == thread_id))
3698 {
3699 m_threads.erase (it);
3700 return true;
3701 }
3702 }
3703
3704 // Didn't find it.
3705 return false;
3706}
3707
3708NativeThreadProtocolSP
3709NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3710{
3711 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3712
3713 Mutex::Locker locker (m_threads_mutex);
3714
3715 if (log)
3716 {
3717 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3718 __FUNCTION__,
3719 GetID (),
3720 thread_id);
3721 }
3722
3723 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3724
3725 // If this is the first thread, save it as the current thread
3726 if (m_threads.empty ())
3727 SetCurrentThreadID (thread_id);
3728
3729 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3730 m_threads.push_back (thread_sp);
3731
3732 return thread_sp;
3733}
3734
3735NativeThreadProtocolSP
3736NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3737{
3738 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3739
3740 Mutex::Locker locker (m_threads_mutex);
3741 if (log)
3742 {
3743 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3744 __FUNCTION__,
3745 GetID (),
3746 thread_id);
3747 }
3748
3749 // Retrieve the thread if it is already getting tracked.
3750 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3751 if (thread_sp)
3752 {
3753 if (log)
3754 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3755 __FUNCTION__,
3756 GetID (),
3757 thread_id);
3758 created = false;
3759 return thread_sp;
3760
3761 }
3762
3763 // Create the thread metadata since it isn't being tracked.
3764 if (log)
3765 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3766 __FUNCTION__,
3767 GetID (),
3768 thread_id);
3769
3770 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3771 m_threads.push_back (thread_sp);
3772 created = true;
3773
3774 return thread_sp;
3775}
3776
3777Error
3778NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3779{
Todd Fiala75f47c32014-10-11 21:42:09 +00003780 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003781
3782 Error error;
3783
3784 // Get a linux thread pointer.
3785 if (!thread_sp)
3786 {
3787 error.SetErrorString ("null thread_sp");
3788 if (log)
3789 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3790 return error;
3791 }
3792 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get());
3793
3794 // Find out the size of a breakpoint (might depend on where we are in the code).
3795 NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext ();
3796 if (!context_sp)
3797 {
3798 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3799 if (log)
3800 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3801 return error;
3802 }
3803
3804 uint32_t breakpoint_size = 0;
3805 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3806 if (error.Fail ())
3807 {
3808 if (log)
3809 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3810 return error;
3811 }
3812 else
3813 {
3814 if (log)
3815 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3816 }
3817
3818 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3819 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3820 lldb::addr_t breakpoint_addr = initial_pc_addr;
3821 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3822 {
3823 // Do not allow breakpoint probe to wrap around.
3824 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3825 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3826 }
3827
3828 // Check if we stopped because of a breakpoint.
3829 NativeBreakpointSP breakpoint_sp;
3830 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3831 if (!error.Success () || !breakpoint_sp)
3832 {
3833 // We didn't find one at a software probe location. Nothing to do.
3834 if (log)
3835 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3836 return Error ();
3837 }
3838
3839 // If the breakpoint is not a software breakpoint, nothing to do.
3840 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3841 {
3842 if (log)
3843 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3844 return Error ();
3845 }
3846
3847 //
3848 // We have a software breakpoint and need to adjust the PC.
3849 //
3850
3851 // Sanity check.
3852 if (breakpoint_size == 0)
3853 {
3854 // Nothing to do! How did we get here?
3855 if (log)
3856 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", it is software, but the size is zero, nothing to do (unexpected)", __FUNCTION__, GetID (), breakpoint_addr);
3857 return Error ();
3858 }
3859
3860 // Change the program counter.
3861 if (log)
3862 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_p->GetID (), initial_pc_addr, breakpoint_addr);
3863
3864 error = context_sp->SetPC (breakpoint_addr);
3865 if (error.Fail ())
3866 {
3867 if (log)
3868 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ());
3869 return error;
3870 }
3871
3872 return error;
3873}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003874
3875void
3876NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3877{
3878 const bool is_stopped = true;
3879 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3880}
3881
3882void
3883NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3884{
3885 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3886}
3887
3888void
3889NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3890{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003891 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003892}
3893
3894void
3895NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3896 const std::function<void (lldb::tid_t tid)> &call_after_function)
3897{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003898 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3899 if (log)
3900 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3901
Chaoren Linfa03ad22015-02-03 01:50:42 +00003902 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003903 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003904 [=](lldb::tid_t request_stop_tid)
3905 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003906 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003907 },
3908 call_after_function,
3909 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003910}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003911
Chaoren Lin03f12d62015-02-03 01:50:49 +00003912void
3913NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3914 lldb::tid_t skip_stop_request_tid,
3915 const std::function<void (lldb::tid_t tid)> &call_after_function)
3916{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003917 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3918 if (log)
3919 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3920
Chaoren Lin03f12d62015-02-03 01:50:49 +00003921 const lldb::pid_t pid = GetID ();
3922 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3923 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3924 [=](lldb::tid_t request_stop_tid)
3925 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003926 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003927 },
3928 call_after_function,
3929 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003930}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003931
3932lldb_private::Error
3933NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3934{
3935 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3936 if (log)
3937 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3938
3939 Error err;
3940 errno = 0;
3941 if (::tgkill (pid, tid, SIGSTOP) != 0)
3942 {
3943 err.SetErrorToErrno ();
3944 if (log)
3945 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3946 }
3947
3948 return err;
3949}