blob: a72b6a24063a5caaa43c50fc0d97c441800cfa5c [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"
38#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000039#include "lldb/Host/HostInfo.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Symbol/ObjectFile.h"
Chaoren Lin2fe1d0a2015-02-03 01:51:38 +000042#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Target/ProcessLaunchInfo.h"
44#include "lldb/Utility/PseudoTerminal.h"
45
Chaoren Lin2fe1d0a2015-02-03 01:51:38 +000046#include "lldb/Host/common/NativeBreakpoint.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "Utility/StringExtractor.h"
48
49#include "Plugins/Process/Utility/LinuxSignals.h"
50#include "NativeThreadLinux.h"
51#include "ProcFileReader.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000052#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
54
Tamas Berghammerd8584872015-02-06 10:57:40 +000055// System includes - They have to be included after framework includes because they define some
56// macros which collide with variable names in other modules
57#include <linux/unistd.h>
58#ifndef __ANDROID__
59#include <sys/procfs.h>
60#endif
61#include <sys/personality.h>
62#include <sys/ptrace.h>
63#include <sys/socket.h>
64#include <sys/syscall.h>
65#include <sys/types.h>
66#include <sys/uio.h>
67#include <sys/user.h>
68#include <sys/wait.h>
69
Todd Fialacacde7d2014-09-27 16:54:22 +000070#ifdef __ANDROID__
71#define __ptrace_request int
72#define PT_DETACH PTRACE_DETACH
73#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000074
75#define DEBUG_PTRACE_MAXBYTES 20
76
77// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000078#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000079#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000080 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000081#endif
Todd Fialadda61942014-07-02 21:34:04 +000082#endif
83#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000084#ifndef PTRACE_SETREGS
85 #define PTRACE_SETREGS 13
86#endif
Todd Fialadda61942014-07-02 21:34:04 +000087#endif
88#ifndef PT_GETFPREGS
89#ifndef PTRACE_GETFPREGS
90 #define PTRACE_GETFPREGS 14
91#endif
92#endif
93#ifndef PT_SETFPREGS
94#ifndef PTRACE_SETFPREGS
95 #define PTRACE_SETFPREGS 15
96#endif
97#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000098#ifndef PTRACE_GETREGSET
99 #define PTRACE_GETREGSET 0x4204
100#endif
101#ifndef PTRACE_SETREGSET
102 #define PTRACE_SETREGSET 0x4205
103#endif
104#ifndef PTRACE_GET_THREAD_AREA
105 #define PTRACE_GET_THREAD_AREA 25
106#endif
107#ifndef PTRACE_ARCH_PRCTL
108 #define PTRACE_ARCH_PRCTL 30
109#endif
110#ifndef ARCH_GET_FS
111 #define ARCH_SET_GS 0x1001
112 #define ARCH_SET_FS 0x1002
113 #define ARCH_GET_FS 0x1003
114 #define ARCH_GET_GS 0x1004
115#endif
116
Todd Fiala0bce1b62014-08-17 00:10:50 +0000117#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000118
119// Support hardware breakpoints in case it has not been defined
120#ifndef TRAP_HWBKPT
121 #define TRAP_HWBKPT 4
122#endif
123
124// Try to define a macro to encapsulate the tgkill syscall
125// fall back on kill() if tgkill isn't available
126#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
127
128// We disable the tracing of ptrace calls for integration builds to
129// avoid the additional indirection and checks.
130#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000131#define PTRACE(req, pid, addr, data, data_size, error) \
132 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000133#else
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))
Todd Fialaaf245d12014-06-30 21:05:18 +0000136#endif
137
138// Private bits we only need internally.
139namespace
140{
141 using namespace lldb;
142 using namespace lldb_private;
143
144 const UnixSignals&
145 GetUnixSignals ()
146 {
147 static process_linux::LinuxSignals signals;
148 return signals;
149 }
150
Chaoren Linfa03ad22015-02-03 01:50:42 +0000151 ThreadStateCoordinator::LogFunction
152 GetThreadLoggerFunction ()
153 {
154 return [](const char *format, va_list args)
155 {
156 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
157 if (log)
158 log->VAPrintf (format, args);
159 };
160 }
161
162 void
163 CoordinatorErrorHandler (const std::string &error_message)
164 {
165 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
166 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000167 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000168 assert (false && "ThreadStateCoordinator error reported");
169 }
170
Todd Fialaaf245d12014-06-30 21:05:18 +0000171 Error
172 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
173 {
174 // Grab process info for the running process.
175 ProcessInstanceInfo process_info;
176 if (!platform.GetProcessInfo (pid, process_info))
177 return lldb_private::Error("failed to get process info");
178
179 // Resolve the executable module.
180 ModuleSP exe_module_sp;
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000181 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), platform.GetSystemArchitecture ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000182 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
183 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000184 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000185 exe_module_sp,
186 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
187
188 if (!error.Success ())
189 return error;
190
191 // Check if we've got our architecture from the exe_module.
192 arch = exe_module_sp->GetArchitecture ();
193 if (arch.IsValid ())
194 return Error();
195 else
196 return Error("failed to retrieve a valid architecture from the exe module");
197 }
198
199 void
200 DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
201 {
202 uint8_t *ptr = (uint8_t *)bytes;
203 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
204 for(uint32_t i=0; i<loop_count; i++)
205 {
206 s.Printf ("[%x]", *ptr);
207 ptr++;
208 }
209 }
210
211 void
212 PtraceDisplayBytes(int &req, void *data, size_t data_size)
213 {
214 StreamString buf;
215 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
216 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
217
218 if (verbose_log)
219 {
220 switch(req)
221 {
222 case PTRACE_POKETEXT:
223 {
224 DisplayBytes(buf, &data, 8);
225 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
226 break;
227 }
228 case PTRACE_POKEDATA:
229 {
230 DisplayBytes(buf, &data, 8);
231 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
232 break;
233 }
234 case PTRACE_POKEUSER:
235 {
236 DisplayBytes(buf, &data, 8);
237 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
238 break;
239 }
240 case PTRACE_SETREGS:
241 {
242 DisplayBytes(buf, data, data_size);
243 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
244 break;
245 }
246 case PTRACE_SETFPREGS:
247 {
248 DisplayBytes(buf, data, data_size);
249 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
250 break;
251 }
252 case PTRACE_SETSIGINFO:
253 {
254 DisplayBytes(buf, data, sizeof(siginfo_t));
255 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
256 break;
257 }
258 case PTRACE_SETREGSET:
259 {
260 // Extract iov_base from data, which is a pointer to the struct IOVEC
261 DisplayBytes(buf, *(void **)data, data_size);
262 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
263 break;
264 }
265 default:
266 {
267 }
268 }
269 }
270 }
271
272 // Wrapper for ptrace to catch errors and log calls.
273 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
274 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000275 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
276 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000277 {
278 long int result;
279
280 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
281
282 PtraceDisplayBytes(req, data, data_size);
283
Chaoren Lin97ccc292015-02-03 01:51:12 +0000284 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000285 errno = 0;
286 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000287 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000288 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000289 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000290
Chaoren Lin97ccc292015-02-03 01:51:12 +0000291 if (result == -1)
292 error.SetErrorToErrno();
293
Todd Fialaaf245d12014-06-30 21:05:18 +0000294 if (log)
295 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
296 reqName, pid, addr, data, data_size, result, file, line);
297
298 PtraceDisplayBytes(req, data, data_size);
299
Chaoren Lin97ccc292015-02-03 01:51:12 +0000300 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000301 {
302 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000303 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000304 {
305 case ESRCH: str = "ESRCH"; break;
306 case EINVAL: str = "EINVAL"; break;
307 case EBUSY: str = "EBUSY"; break;
308 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000309 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000310 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000311 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000312 }
313
314 return result;
315 }
316
317#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
318 // Wrapper for ptrace when logging is not required.
319 // Sets errno to 0 prior to calling ptrace.
320 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000321 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000322 {
323 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000324
325 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000326 errno = 0;
327 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000328 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000329 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000330 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000331
332 if (result == -1)
333 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 return result;
335 }
336#endif
337
338 //------------------------------------------------------------------------------
339 // Static implementations of NativeProcessLinux::ReadMemory and
340 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
341 // functions without needed to go thru the thread funnel.
342
Chaoren Lin97ccc292015-02-03 01:51:12 +0000343 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000344 DoReadMemory (
345 lldb::pid_t pid,
346 lldb::addr_t vm_addr,
347 void *buf,
348 lldb::addr_t size,
349 Error &error)
350 {
351 // ptrace word size is determined by the host, not the child
352 static const unsigned word_size = sizeof(void*);
353 unsigned char *dst = static_cast<unsigned char*>(buf);
354 lldb::addr_t bytes_read;
355 lldb::addr_t remainder;
356 long data;
357
358 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
359 if (log)
360 ProcessPOSIXLog::IncNestLevel();
361 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
362 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
363 pid, word_size, (void*)vm_addr, buf, size);
364
365 assert(sizeof(data) >= word_size);
366 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
367 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000368 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
369 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000370 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000371 if (log)
372 ProcessPOSIXLog::DecNestLevel();
373 return bytes_read;
374 }
375
376 remainder = size - bytes_read;
377 remainder = remainder > word_size ? word_size : remainder;
378
379 // Copy the data into our buffer
380 for (unsigned i = 0; i < remainder; ++i)
381 dst[i] = ((data >> i*8) & 0xFF);
382
383 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
384 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
385 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
386 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
387 {
388 uintptr_t print_dst = 0;
389 // Format bytes from data by moving into print_dst for log output
390 for (unsigned i = 0; i < remainder; ++i)
391 print_dst |= (((data >> i*8) & 0xFF) << i*8);
392 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
393 (void*)vm_addr, print_dst, (unsigned long)data);
394 }
395
396 vm_addr += word_size;
397 dst += word_size;
398 }
399
400 if (log)
401 ProcessPOSIXLog::DecNestLevel();
402 return bytes_read;
403 }
404
Chaoren Lin97ccc292015-02-03 01:51:12 +0000405 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000406 DoWriteMemory(
407 lldb::pid_t pid,
408 lldb::addr_t vm_addr,
409 const void *buf,
410 lldb::addr_t size,
411 Error &error)
412 {
413 // ptrace word size is determined by the host, not the child
414 static const unsigned word_size = sizeof(void*);
415 const unsigned char *src = static_cast<const unsigned char*>(buf);
416 lldb::addr_t bytes_written = 0;
417 lldb::addr_t remainder;
418
419 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
420 if (log)
421 ProcessPOSIXLog::IncNestLevel();
422 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
423 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
424 pid, word_size, (void*)vm_addr, buf, size);
425
426 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
427 {
428 remainder = size - bytes_written;
429 remainder = remainder > word_size ? word_size : remainder;
430
431 if (remainder == word_size)
432 {
433 unsigned long data = 0;
434 assert(sizeof(data) >= word_size);
435 for (unsigned i = 0; i < word_size; ++i)
436 data |= (unsigned long)src[i] << i*8;
437
438 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
439 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
440 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
441 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
442 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
443 (void*)vm_addr, *(unsigned long*)src, data);
444
Chaoren Lin97ccc292015-02-03 01:51:12 +0000445 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000446 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000447 if (log)
448 ProcessPOSIXLog::DecNestLevel();
449 return bytes_written;
450 }
451 }
452 else
453 {
454 unsigned char buff[8];
455 if (DoReadMemory(pid, vm_addr,
456 buff, word_size, error) != word_size)
457 {
458 if (log)
459 ProcessPOSIXLog::DecNestLevel();
460 return bytes_written;
461 }
462
463 memcpy(buff, src, remainder);
464
465 if (DoWriteMemory(pid, vm_addr,
466 buff, word_size, error) != word_size)
467 {
468 if (log)
469 ProcessPOSIXLog::DecNestLevel();
470 return bytes_written;
471 }
472
473 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
474 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
475 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
476 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
477 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
478 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
479 }
480
481 vm_addr += word_size;
482 src += word_size;
483 }
484 if (log)
485 ProcessPOSIXLog::DecNestLevel();
486 return bytes_written;
487 }
488
489 //------------------------------------------------------------------------------
490 /// @class Operation
491 /// @brief Represents a NativeProcessLinux operation.
492 ///
493 /// Under Linux, it is not possible to ptrace() from any other thread but the
494 /// one that spawned or attached to the process from the start. Therefore, when
495 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
496 /// process the operation must be "funneled" to a specific thread to perform the
497 /// task. The Operation class provides an abstract base for all services the
498 /// NativeProcessLinux must perform via the single virtual function Execute, thus
499 /// encapsulating the code that needs to run in the privileged context.
500 class Operation
501 {
502 public:
503 Operation () : m_error() { }
504
505 virtual
506 ~Operation() {}
507
508 virtual void
509 Execute (NativeProcessLinux *process) = 0;
510
511 const Error &
512 GetError () const { return m_error; }
513
514 protected:
515 Error m_error;
516 };
517
518 //------------------------------------------------------------------------------
519 /// @class ReadOperation
520 /// @brief Implements NativeProcessLinux::ReadMemory.
521 class ReadOperation : public Operation
522 {
523 public:
524 ReadOperation (
525 lldb::addr_t addr,
526 void *buff,
527 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000528 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000529 Operation (),
530 m_addr (addr),
531 m_buff (buff),
532 m_size (size),
533 m_result (result)
534 {
535 }
536
537 void Execute (NativeProcessLinux *process) override;
538
539 private:
540 lldb::addr_t m_addr;
541 void *m_buff;
542 lldb::addr_t m_size;
543 lldb::addr_t &m_result;
544 };
545
546 void
547 ReadOperation::Execute (NativeProcessLinux *process)
548 {
549 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
550 }
551
552 //------------------------------------------------------------------------------
553 /// @class WriteOperation
554 /// @brief Implements NativeProcessLinux::WriteMemory.
555 class WriteOperation : public Operation
556 {
557 public:
558 WriteOperation (
559 lldb::addr_t addr,
560 const void *buff,
561 lldb::addr_t size,
562 lldb::addr_t &result) :
563 Operation (),
564 m_addr (addr),
565 m_buff (buff),
566 m_size (size),
567 m_result (result)
568 {
569 }
570
571 void Execute (NativeProcessLinux *process) override;
572
573 private:
574 lldb::addr_t m_addr;
575 const void *m_buff;
576 lldb::addr_t m_size;
577 lldb::addr_t &m_result;
578 };
579
580 void
581 WriteOperation::Execute(NativeProcessLinux *process)
582 {
583 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
584 }
585
586 //------------------------------------------------------------------------------
587 /// @class ReadRegOperation
588 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
589 class ReadRegOperation : public Operation
590 {
591 public:
592 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000593 RegisterValue &value)
594 : m_tid(tid),
595 m_offset(static_cast<uintptr_t> (offset)),
596 m_reg_name(reg_name),
597 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000598 { }
599
600 void Execute(NativeProcessLinux *monitor);
601
602 private:
603 lldb::tid_t m_tid;
604 uintptr_t m_offset;
605 const char *m_reg_name;
606 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000607 };
608
609 void
610 ReadRegOperation::Execute(NativeProcessLinux *monitor)
611 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000612#if defined (__arm64__) || defined (__aarch64__)
613 if (m_offset > sizeof(struct user_pt_regs))
614 {
615 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
616 if (offset > sizeof(struct user_fpsimd_state))
617 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000618 m_error.SetErrorString("invalid offset value");
619 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000620 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000621 elf_fpregset_t regs;
622 int regset = NT_FPREGSET;
623 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000624
Chaoren Lin97ccc292015-02-03 01:51:12 +0000625 ioVec.iov_base = &regs;
626 ioVec.iov_len = sizeof regs;
627 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
628 if (m_error.Success())
629 {
630 lldb_private::ArchSpec arch;
631 if (monitor->GetArchitecture(arch))
632 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000633 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000634 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000635 }
636 }
637 else
638 {
639 elf_gregset_t regs;
640 int regset = NT_PRSTATUS;
641 struct iovec ioVec;
642
643 ioVec.iov_base = &regs;
644 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000645 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
646 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000647 {
648 lldb_private::ArchSpec arch;
649 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000650 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000651 else
652 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000653 }
654 }
655#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000656 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
657
Chaoren Lin97ccc292015-02-03 01:51:12 +0000658 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error);
659 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000660 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000661
Todd Fialaaf245d12014-06-30 21:05:18 +0000662 if (log)
663 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
664 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000665#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000666 }
667
668 //------------------------------------------------------------------------------
669 /// @class WriteRegOperation
670 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
671 class WriteRegOperation : public Operation
672 {
673 public:
674 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000675 const RegisterValue &value)
676 : m_tid(tid),
677 m_offset(offset),
678 m_reg_name(reg_name),
679 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000680 { }
681
682 void Execute(NativeProcessLinux *monitor);
683
684 private:
685 lldb::tid_t m_tid;
686 uintptr_t m_offset;
687 const char *m_reg_name;
688 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000689 };
690
691 void
692 WriteRegOperation::Execute(NativeProcessLinux *monitor)
693 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000694#if defined (__arm64__) || defined (__aarch64__)
695 if (m_offset > sizeof(struct user_pt_regs))
696 {
697 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
698 if (offset > sizeof(struct user_fpsimd_state))
699 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000700 m_error.SetErrorString("invalid offset value");
701 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000702 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000703 elf_fpregset_t regs;
704 int regset = NT_FPREGSET;
705 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000706
Chaoren Lin97ccc292015-02-03 01:51:12 +0000707 ioVec.iov_base = &regs;
708 ioVec.iov_len = sizeof regs;
709 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
710 if (m_error.Sucess())
711 {
712 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
713 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000714 }
715 }
716 else
717 {
718 elf_gregset_t regs;
719 int regset = NT_PRSTATUS;
720 struct iovec ioVec;
721
722 ioVec.iov_base = &regs;
723 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000724 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
725 if (m_error.Sucess())
Todd Fiala0fceef82014-09-15 17:09:23 +0000726 {
727 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000728 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000729 }
730 }
731#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000732 void* buf;
733 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
734
735 buf = (void*) m_value.GetAsUInt64();
736
737 if (log)
738 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000739 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000740#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000741 }
742
743 //------------------------------------------------------------------------------
744 /// @class ReadGPROperation
745 /// @brief Implements NativeProcessLinux::ReadGPR.
746 class ReadGPROperation : public Operation
747 {
748 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000749 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
750 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000751 { }
752
753 void Execute(NativeProcessLinux *monitor);
754
755 private:
756 lldb::tid_t m_tid;
757 void *m_buf;
758 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000759 };
760
761 void
762 ReadGPROperation::Execute(NativeProcessLinux *monitor)
763 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000764#if defined (__arm64__) || defined (__aarch64__)
765 int regset = NT_PRSTATUS;
766 struct iovec ioVec;
767
768 ioVec.iov_base = m_buf;
769 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000770 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000771#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000772 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000773#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000774 }
775
776 //------------------------------------------------------------------------------
777 /// @class ReadFPROperation
778 /// @brief Implements NativeProcessLinux::ReadFPR.
779 class ReadFPROperation : public Operation
780 {
781 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000782 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
783 : m_tid(tid),
784 m_buf(buf),
785 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000786 { }
787
788 void Execute(NativeProcessLinux *monitor);
789
790 private:
791 lldb::tid_t m_tid;
792 void *m_buf;
793 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000794 };
795
796 void
797 ReadFPROperation::Execute(NativeProcessLinux *monitor)
798 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000799#if defined (__arm64__) || defined (__aarch64__)
800 int regset = NT_FPREGSET;
801 struct iovec ioVec;
802
803 ioVec.iov_base = m_buf;
804 ioVec.iov_len = m_buf_size;
805 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
806 m_result = false;
807 else
808 m_result = true;
809#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000810 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000811#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000812 }
813
814 //------------------------------------------------------------------------------
815 /// @class ReadRegisterSetOperation
816 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
817 class ReadRegisterSetOperation : public Operation
818 {
819 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000820 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
821 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000822 { }
823
824 void Execute(NativeProcessLinux *monitor);
825
826 private:
827 lldb::tid_t m_tid;
828 void *m_buf;
829 size_t m_buf_size;
830 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000831 };
832
833 void
834 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
835 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000836 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000837 }
838
839 //------------------------------------------------------------------------------
840 /// @class WriteGPROperation
841 /// @brief Implements NativeProcessLinux::WriteGPR.
842 class WriteGPROperation : public Operation
843 {
844 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000845 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
846 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000847 { }
848
849 void Execute(NativeProcessLinux *monitor);
850
851 private:
852 lldb::tid_t m_tid;
853 void *m_buf;
854 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000855 };
856
857 void
858 WriteGPROperation::Execute(NativeProcessLinux *monitor)
859 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000860#if defined (__arm64__) || defined (__aarch64__)
861 int regset = NT_PRSTATUS;
862 struct iovec ioVec;
863
864 ioVec.iov_base = m_buf;
865 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000866 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000867#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000868 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000869#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000870 }
871
872 //------------------------------------------------------------------------------
873 /// @class WriteFPROperation
874 /// @brief Implements NativeProcessLinux::WriteFPR.
875 class WriteFPROperation : public Operation
876 {
877 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000878 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
879 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000880 { }
881
882 void Execute(NativeProcessLinux *monitor);
883
884 private:
885 lldb::tid_t m_tid;
886 void *m_buf;
887 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000888 };
889
890 void
891 WriteFPROperation::Execute(NativeProcessLinux *monitor)
892 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000893#if defined (__arm64__) || defined (__aarch64__)
894 int regset = NT_FPREGSET;
895 struct iovec ioVec;
896
897 ioVec.iov_base = m_buf;
898 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000899 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000900#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000901 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000902#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000903 }
904
905 //------------------------------------------------------------------------------
906 /// @class WriteRegisterSetOperation
907 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
908 class WriteRegisterSetOperation : public Operation
909 {
910 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000911 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
912 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000913 { }
914
915 void Execute(NativeProcessLinux *monitor);
916
917 private:
918 lldb::tid_t m_tid;
919 void *m_buf;
920 size_t m_buf_size;
921 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000922 };
923
924 void
925 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
926 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000927 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000928 }
929
930 //------------------------------------------------------------------------------
931 /// @class ResumeOperation
932 /// @brief Implements NativeProcessLinux::Resume.
933 class ResumeOperation : public Operation
934 {
935 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000936 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
937 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000938
939 void Execute(NativeProcessLinux *monitor);
940
941 private:
942 lldb::tid_t m_tid;
943 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000944 };
945
946 void
947 ResumeOperation::Execute(NativeProcessLinux *monitor)
948 {
949 intptr_t data = 0;
950
951 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
952 data = m_signo;
953
Chaoren Lin97ccc292015-02-03 01:51:12 +0000954 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
955 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000956 {
957 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
958
959 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000960 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000961 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000962 }
963
964 //------------------------------------------------------------------------------
965 /// @class SingleStepOperation
966 /// @brief Implements NativeProcessLinux::SingleStep.
967 class SingleStepOperation : public Operation
968 {
969 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000970 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
971 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000972
973 void Execute(NativeProcessLinux *monitor);
974
975 private:
976 lldb::tid_t m_tid;
977 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000978 };
979
980 void
981 SingleStepOperation::Execute(NativeProcessLinux *monitor)
982 {
983 intptr_t data = 0;
984
985 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
986 data = m_signo;
987
Chaoren Lin97ccc292015-02-03 01:51:12 +0000988 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000989 }
990
991 //------------------------------------------------------------------------------
992 /// @class SiginfoOperation
993 /// @brief Implements NativeProcessLinux::GetSignalInfo.
994 class SiginfoOperation : public Operation
995 {
996 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000997 SiginfoOperation(lldb::tid_t tid, void *info)
998 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000999
1000 void Execute(NativeProcessLinux *monitor);
1001
1002 private:
1003 lldb::tid_t m_tid;
1004 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001005 };
1006
1007 void
1008 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1009 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001010 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001011 }
1012
1013 //------------------------------------------------------------------------------
1014 /// @class EventMessageOperation
1015 /// @brief Implements NativeProcessLinux::GetEventMessage.
1016 class EventMessageOperation : public Operation
1017 {
1018 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001019 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1020 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001021
1022 void Execute(NativeProcessLinux *monitor);
1023
1024 private:
1025 lldb::tid_t m_tid;
1026 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001027 };
1028
1029 void
1030 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1031 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001032 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001033 }
1034
1035 class DetachOperation : public Operation
1036 {
1037 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001038 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001039
1040 void Execute(NativeProcessLinux *monitor);
1041
1042 private:
1043 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001044 };
1045
1046 void
1047 DetachOperation::Execute(NativeProcessLinux *monitor)
1048 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001049 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001050 }
1051
1052}
1053
1054using namespace lldb_private;
1055
1056// Simple helper function to ensure flags are enabled on the given file
1057// descriptor.
1058static bool
1059EnsureFDFlags(int fd, int flags, Error &error)
1060{
1061 int status;
1062
1063 if ((status = fcntl(fd, F_GETFL)) == -1)
1064 {
1065 error.SetErrorToErrno();
1066 return false;
1067 }
1068
1069 if (fcntl(fd, F_SETFL, status | flags) == -1)
1070 {
1071 error.SetErrorToErrno();
1072 return false;
1073 }
1074
1075 return true;
1076}
1077
1078NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1079 : m_monitor(monitor)
1080{
1081 sem_init(&m_semaphore, 0, 0);
1082}
1083
1084NativeProcessLinux::OperationArgs::~OperationArgs()
1085{
1086 sem_destroy(&m_semaphore);
1087}
1088
1089NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
1090 lldb_private::Module *module,
1091 char const **argv,
1092 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001093 const std::string &stdin_path,
1094 const std::string &stdout_path,
1095 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001096 const char *working_dir,
1097 const lldb_private::ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001098 : OperationArgs(monitor),
1099 m_module(module),
1100 m_argv(argv),
1101 m_envp(envp),
1102 m_stdin_path(stdin_path),
1103 m_stdout_path(stdout_path),
1104 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001105 m_working_dir(working_dir),
1106 m_launch_info(launch_info)
1107{
1108}
Todd Fialaaf245d12014-06-30 21:05:18 +00001109
1110NativeProcessLinux::LaunchArgs::~LaunchArgs()
1111{ }
1112
1113NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1114 lldb::pid_t pid)
1115 : OperationArgs(monitor), m_pid(pid) { }
1116
1117NativeProcessLinux::AttachArgs::~AttachArgs()
1118{ }
1119
1120// -----------------------------------------------------------------------------
1121// Public Static Methods
1122// -----------------------------------------------------------------------------
1123
1124lldb_private::Error
1125NativeProcessLinux::LaunchProcess (
1126 lldb_private::Module *exe_module,
1127 lldb_private::ProcessLaunchInfo &launch_info,
1128 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1129 NativeProcessProtocolSP &native_process_sp)
1130{
1131 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1132
1133 Error error;
1134
1135 // Verify the working directory is valid if one was specified.
1136 const char* working_dir = launch_info.GetWorkingDirectory ();
1137 if (working_dir)
1138 {
1139 FileSpec working_dir_fs (working_dir, true);
1140 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1141 {
1142 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1143 return error;
1144 }
1145 }
1146
Zachary Turner696b5282014-08-14 16:01:25 +00001147 const lldb_private::FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001148
1149 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001150 std::string stdin_path;
1151 std::string stdout_path;
1152 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001153
1154 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001155 if (file_action)
1156 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001157
1158 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001159 if (file_action)
1160 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001161
1162 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001163 if (file_action)
1164 stderr_path = file_action->GetPath ();
1165
1166 if (log)
1167 {
1168 if (!stdin_path.empty ())
1169 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1170 else
1171 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1172
1173 if (!stdout_path.empty ())
1174 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1175 else
1176 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1177
1178 if (!stderr_path.empty ())
1179 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1180 else
1181 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1182 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001183
1184 // Create the NativeProcessLinux in launch mode.
1185 native_process_sp.reset (new NativeProcessLinux ());
1186
1187 if (log)
1188 {
1189 int i = 0;
1190 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1191 {
1192 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1193 ++i;
1194 }
1195 }
1196
1197 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1198 {
1199 native_process_sp.reset ();
1200 error.SetErrorStringWithFormat ("failed to register the native delegate");
1201 return error;
1202 }
1203
1204 reinterpret_cast<NativeProcessLinux*> (native_process_sp.get ())->LaunchInferior (
1205 exe_module,
1206 launch_info.GetArguments ().GetConstArgumentVector (),
1207 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1208 stdin_path,
1209 stdout_path,
1210 stderr_path,
1211 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001212 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001213 error);
1214
1215 if (error.Fail ())
1216 {
1217 native_process_sp.reset ();
1218 if (log)
1219 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1220 return error;
1221 }
1222
1223 launch_info.SetProcessID (native_process_sp->GetID ());
1224
1225 return error;
1226}
1227
1228lldb_private::Error
1229NativeProcessLinux::AttachToProcess (
1230 lldb::pid_t pid,
1231 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1232 NativeProcessProtocolSP &native_process_sp)
1233{
1234 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1235 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1236 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1237
1238 // Grab the current platform architecture. This should be Linux,
1239 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001240 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 if (!platform_sp)
1242 return Error("failed to get a valid default platform");
1243
1244 // Retrieve the architecture for the running process.
1245 ArchSpec process_arch;
1246 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1247 if (!error.Success ())
1248 return error;
1249
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001250 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001251
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001252 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001253 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001254 error.SetErrorStringWithFormat ("failed to register the native delegate");
1255 return error;
1256 }
1257
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001258 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001260 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001261
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001262 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001263 return error;
1264}
1265
1266// -----------------------------------------------------------------------------
1267// Public Instance Methods
1268// -----------------------------------------------------------------------------
1269
1270NativeProcessLinux::NativeProcessLinux () :
1271 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1272 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001273 m_operation_thread (),
1274 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001275 m_operation (nullptr),
1276 m_operation_mutex (),
1277 m_operation_pending (),
1278 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001279 m_supports_mem_region (eLazyBoolCalculate),
1280 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001281 m_mem_region_cache_mutex (),
1282 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1283 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001284{
1285}
1286
1287//------------------------------------------------------------------------------
1288/// The basic design of the NativeProcessLinux is built around two threads.
1289///
1290/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1291/// for changes in the debugee state. When a change is detected a
1292/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1293/// "drives" state changes in the debugger.
1294///
1295/// The second thread (@see OperationThread) is responsible for two things 1)
1296/// launching or attaching to the inferior process, and then 2) servicing
1297/// operations such as register reads/writes, stepping, etc. See the comments
1298/// on the Operation class for more info as to why this is needed.
1299void
1300NativeProcessLinux::LaunchInferior (
1301 Module *module,
1302 const char *argv[],
1303 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001304 const std::string &stdin_path,
1305 const std::string &stdout_path,
1306 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001307 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001308 const lldb_private::ProcessLaunchInfo &launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001309 lldb_private::Error &error)
1310{
1311 if (module)
1312 m_arch = module->GetArchitecture ();
1313
Chaoren Linfa03ad22015-02-03 01:50:42 +00001314 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001315
1316 std::unique_ptr<LaunchArgs> args(
1317 new LaunchArgs(
1318 this, module, argv, envp,
1319 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001320 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001321
Chaoren Linfa03ad22015-02-03 01:50:42 +00001322 sem_init (&m_operation_pending, 0, 0);
1323 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001324
Chaoren Linfa03ad22015-02-03 01:50:42 +00001325 StartLaunchOpThread (args.get(), error);
1326 if (!error.Success ())
1327 return;
1328
1329 error = StartCoordinatorThread ();
1330 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001331 return;
1332
1333WAIT_AGAIN:
1334 // Wait for the operation thread to initialize.
1335 if (sem_wait(&args->m_semaphore))
1336 {
1337 if (errno == EINTR)
1338 goto WAIT_AGAIN;
1339 else
1340 {
1341 error.SetErrorToErrno();
1342 return;
1343 }
1344 }
1345
1346 // Check that the launch was a success.
1347 if (!args->m_error.Success())
1348 {
1349 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001350 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001351 error = args->m_error;
1352 return;
1353 }
1354
1355 // Finally, start monitoring the child process for change in state.
1356 m_monitor_thread = Host::StartMonitoringChildProcess(
1357 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001358 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001359 {
1360 error.SetErrorToGenericError();
1361 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1362 return;
1363 }
1364}
1365
1366void
1367NativeProcessLinux::AttachToInferior (lldb::pid_t pid, lldb_private::Error &error)
1368{
1369 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1370 if (log)
1371 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1372
1373 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001374 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001375 if (!platform_sp)
1376 {
1377 if (log)
1378 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1379 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001380 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001381 }
1382
1383 // Gather info about the process.
1384 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001385 if (!platform_sp->GetProcessInfo (pid, process_info))
1386 {
1387 if (log)
1388 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1389 error.SetErrorString ("failed to get process info");
1390 return;
1391 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001392
1393 // Resolve the executable module
1394 ModuleSP exe_module_sp;
1395 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001396 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), HostInfo::GetArchitecture());
1397 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001398 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001399 if (!error.Success())
1400 return;
1401
1402 // Set the architecture to the exe architecture.
1403 m_arch = exe_module_sp->GetArchitecture();
1404 if (log)
1405 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1406
1407 m_pid = pid;
1408 SetState(eStateAttaching);
1409
1410 sem_init (&m_operation_pending, 0, 0);
1411 sem_init (&m_operation_done, 0, 0);
1412
1413 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1414
1415 StartAttachOpThread(args.get (), error);
1416 if (!error.Success ())
1417 return;
1418
Chaoren Linfa03ad22015-02-03 01:50:42 +00001419 error = StartCoordinatorThread ();
1420 if (!error.Success ())
1421 return;
1422
Todd Fialaaf245d12014-06-30 21:05:18 +00001423WAIT_AGAIN:
1424 // Wait for the operation thread to initialize.
1425 if (sem_wait (&args->m_semaphore))
1426 {
1427 if (errno == EINTR)
1428 goto WAIT_AGAIN;
1429 else
1430 {
1431 error.SetErrorToErrno ();
1432 return;
1433 }
1434 }
1435
1436 // Check that the attach was a success.
1437 if (!args->m_error.Success ())
1438 {
1439 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001440 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001441 error = args->m_error;
1442 return;
1443 }
1444
1445 // Finally, start monitoring the child process for change in state.
1446 m_monitor_thread = Host::StartMonitoringChildProcess (
1447 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001448 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001449 {
1450 error.SetErrorToGenericError ();
1451 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1452 return;
1453 }
1454}
1455
1456NativeProcessLinux::~NativeProcessLinux()
1457{
1458 StopMonitor();
1459}
1460
1461//------------------------------------------------------------------------------
1462// Thread setup and tear down.
1463
1464void
1465NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1466{
1467 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1468
Zachary Turneracee96a2014-09-23 18:32:09 +00001469 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001470 return;
1471
Zachary Turner39de3112014-09-09 20:54:56 +00001472 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001473}
1474
1475void *
1476NativeProcessLinux::LaunchOpThread(void *arg)
1477{
1478 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1479
1480 if (!Launch(args)) {
1481 sem_post(&args->m_semaphore);
1482 return NULL;
1483 }
1484
1485 ServeOperation(args);
1486 return NULL;
1487}
1488
1489bool
1490NativeProcessLinux::Launch(LaunchArgs *args)
1491{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001492 assert (args && "null args");
1493 if (!args)
1494 return false;
1495
Todd Fialaaf245d12014-06-30 21:05:18 +00001496 NativeProcessLinux *monitor = args->m_monitor;
1497 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001498
1499 const char **argv = args->m_argv;
1500 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001501 const char *working_dir = args->m_working_dir;
1502
1503 lldb_utility::PseudoTerminal terminal;
1504 const size_t err_len = 1024;
1505 char err_str[err_len];
1506 lldb::pid_t pid;
1507 NativeThreadProtocolSP thread_sp;
1508
1509 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001510
1511 // Propagate the environment if one is not supplied.
1512 if (envp == NULL || envp[0] == NULL)
1513 envp = const_cast<const char **>(environ);
1514
1515 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1516 {
1517 args->m_error.SetErrorToGenericError();
1518 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001519 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001520 }
1521
1522 // Recognized child exit status codes.
1523 enum {
1524 ePtraceFailed = 1,
1525 eDupStdinFailed,
1526 eDupStdoutFailed,
1527 eDupStderrFailed,
1528 eChdirFailed,
1529 eExecFailed,
1530 eSetGidFailed
1531 };
1532
1533 // Child process.
1534 if (pid == 0)
1535 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001536 // FIXME consider opening a pipe between parent/child and have this forked child
1537 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001538
Todd Fiala75f47c32014-10-11 21:42:09 +00001539 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001540 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1541 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001542 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001543
Pavel Labath493c3a12015-02-04 10:36:57 +00001544 // terminal has already dupped the tty descriptors to stdin/out/err.
1545 // This closes original fd from which they were copied (and avoids
1546 // leaking descriptors to the debugged process.
1547 terminal.CloseSlaveFileDescriptor();
1548
Todd Fialaaf245d12014-06-30 21:05:18 +00001549 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001550 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001551 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001552
1553 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001554 if (setpgid(0, 0) != 0)
1555 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001556 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001557 // Don't allow this to prevent an inferior exec.
1558 }
1559
1560 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001561 if (!args->m_stdin_path.empty ())
1562 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001563 exit(eDupStdinFailed);
1564
Todd Fiala75f47c32014-10-11 21:42:09 +00001565 if (!args->m_stdout_path.empty ())
1566 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT))
Todd Fialaaf245d12014-06-30 21:05:18 +00001567 exit(eDupStdoutFailed);
1568
Todd Fiala75f47c32014-10-11 21:42:09 +00001569 if (!args->m_stderr_path.empty ())
1570 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT))
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 exit(eDupStderrFailed);
1572
1573 // Change working directory
1574 if (working_dir != NULL && working_dir[0])
1575 if (0 != ::chdir(working_dir))
1576 exit(eChdirFailed);
1577
Todd Fiala0bce1b62014-08-17 00:10:50 +00001578 // Disable ASLR if requested.
1579 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1580 {
1581 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1582 if (old_personality == -1)
1583 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001584 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001585 }
1586 else
1587 {
1588 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1589 if (new_personality == -1)
1590 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001591 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001592 }
1593 else
1594 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001595 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001596 }
1597 }
1598 }
1599
Todd Fiala75f47c32014-10-11 21:42:09 +00001600 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001601 execve(argv[0],
1602 const_cast<char *const *>(argv),
1603 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001604
1605 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001606 exit(eExecFailed);
1607 }
1608
Todd Fiala75f47c32014-10-11 21:42:09 +00001609 //
1610 // This is the parent code here.
1611 //
1612 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1613
Todd Fialaaf245d12014-06-30 21:05:18 +00001614 // Wait for the child process to trap on its call to execve.
1615 ::pid_t wpid;
1616 int status;
1617 if ((wpid = waitpid(pid, &status, 0)) < 0)
1618 {
1619 args->m_error.SetErrorToErrno();
1620
1621 if (log)
1622 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1623
1624 // Mark the inferior as invalid.
1625 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1626 monitor->SetState (StateType::eStateInvalid);
1627
Todd Fiala75f47c32014-10-11 21:42:09 +00001628 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001629 }
1630 else if (WIFEXITED(status))
1631 {
1632 // open, dup or execve likely failed for some reason.
1633 args->m_error.SetErrorToGenericError();
1634 switch (WEXITSTATUS(status))
1635 {
1636 case ePtraceFailed:
1637 args->m_error.SetErrorString("Child ptrace failed.");
1638 break;
1639 case eDupStdinFailed:
1640 args->m_error.SetErrorString("Child open stdin failed.");
1641 break;
1642 case eDupStdoutFailed:
1643 args->m_error.SetErrorString("Child open stdout failed.");
1644 break;
1645 case eDupStderrFailed:
1646 args->m_error.SetErrorString("Child open stderr failed.");
1647 break;
1648 case eChdirFailed:
1649 args->m_error.SetErrorString("Child failed to set working directory.");
1650 break;
1651 case eExecFailed:
1652 args->m_error.SetErrorString("Child exec failed.");
1653 break;
1654 case eSetGidFailed:
1655 args->m_error.SetErrorString("Child setgid failed.");
1656 break;
1657 default:
1658 args->m_error.SetErrorString("Child returned unknown exit status.");
1659 break;
1660 }
1661
1662 if (log)
1663 {
1664 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1665 __FUNCTION__,
1666 WEXITSTATUS(status));
1667 }
1668
1669 // Mark the inferior as invalid.
1670 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1671 monitor->SetState (StateType::eStateInvalid);
1672
Todd Fiala75f47c32014-10-11 21:42:09 +00001673 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001674 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001675 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001676 "Could not sync with inferior process.");
1677
1678 if (log)
1679 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1680
Chaoren Lin97ccc292015-02-03 01:51:12 +00001681 args->m_error = SetDefaultPtraceOpts(pid);
1682 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001683 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001684 if (log)
1685 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1686 __FUNCTION__,
1687 args->m_error.AsCString ());
1688
1689 // Mark the inferior as invalid.
1690 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1691 monitor->SetState (StateType::eStateInvalid);
1692
Todd Fiala75f47c32014-10-11 21:42:09 +00001693 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 }
1695
1696 // Release the master terminal descriptor and pass it off to the
1697 // NativeProcessLinux instance. Similarly stash the inferior pid.
1698 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1699 monitor->m_pid = pid;
1700
1701 // Set the terminal fd to be in non blocking mode (it simplifies the
1702 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1703 // descriptor to read from).
1704 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1705 {
1706 if (log)
1707 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1708 __FUNCTION__,
1709 args->m_error.AsCString ());
1710
1711 // Mark the inferior as invalid.
1712 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1713 monitor->SetState (StateType::eStateInvalid);
1714
Todd Fiala75f47c32014-10-11 21:42:09 +00001715 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001716 }
1717
1718 if (log)
1719 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1720
Chaoren Linfa03ad22015-02-03 01:50:42 +00001721 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001722 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001723 monitor->NotifyThreadCreateStopped (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001724 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001725
1726 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001727 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001728 monitor->SetState (StateType::eStateStopped);
1729
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 if (log)
1731 {
1732 if (args->m_error.Success ())
1733 {
1734 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1735 }
1736 else
1737 {
1738 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1739 __FUNCTION__,
1740 args->m_error.AsCString ());
1741 }
1742 }
1743 return args->m_error.Success();
1744}
1745
1746void
1747NativeProcessLinux::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1748{
1749 static const char *g_thread_name = "lldb.process.linux.operation";
1750
Zachary Turneracee96a2014-09-23 18:32:09 +00001751 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001752 return;
1753
Zachary Turner39de3112014-09-09 20:54:56 +00001754 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001755}
1756
1757void *
1758NativeProcessLinux::AttachOpThread(void *arg)
1759{
1760 AttachArgs *args = static_cast<AttachArgs*>(arg);
1761
1762 if (!Attach(args)) {
1763 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001764 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 }
1766
1767 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001768 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001769}
1770
1771bool
1772NativeProcessLinux::Attach(AttachArgs *args)
1773{
1774 lldb::pid_t pid = args->m_pid;
1775
1776 NativeProcessLinux *monitor = args->m_monitor;
1777 lldb::ThreadSP inferior;
1778 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1779
1780 // Use a map to keep track of the threads which we have attached/need to attach.
1781 Host::TidMap tids_to_attach;
1782 if (pid <= 1)
1783 {
1784 args->m_error.SetErrorToGenericError();
1785 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1786 goto FINISH;
1787 }
1788
1789 while (Host::FindProcessThreads(pid, tids_to_attach))
1790 {
1791 for (Host::TidMap::iterator it = tids_to_attach.begin();
1792 it != tids_to_attach.end();)
1793 {
1794 if (it->second == false)
1795 {
1796 lldb::tid_t tid = it->first;
1797
1798 // Attach to the requested process.
1799 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001800 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1801 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001802 {
1803 // No such thread. The thread may have exited.
1804 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001805 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001806 {
1807 it = tids_to_attach.erase(it);
1808 continue;
1809 }
1810 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001811 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001812 }
1813
1814 int status;
1815 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1816 // At this point we should have a thread stopped if waitpid succeeds.
1817 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1818 {
1819 // No such thread. The thread may have exited.
1820 // More error handling may be needed.
1821 if (errno == ESRCH)
1822 {
1823 it = tids_to_attach.erase(it);
1824 continue;
1825 }
1826 else
1827 {
1828 args->m_error.SetErrorToErrno();
1829 goto FINISH;
1830 }
1831 }
1832
Chaoren Lin97ccc292015-02-03 01:51:12 +00001833 args->m_error = SetDefaultPtraceOpts(tid);
1834 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001835 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001836
1837
1838 if (log)
1839 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1840
1841 it->second = true;
1842
1843 // Create the thread, mark it as stopped.
1844 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1845 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001846
1847 // This will notify this is a new thread and tell the system it is stopped.
1848 monitor->NotifyThreadCreateStopped (tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001849 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
1850 monitor->SetCurrentThreadID (thread_sp->GetID ());
1851 }
1852
1853 // move the loop forward
1854 ++it;
1855 }
1856 }
1857
1858 if (tids_to_attach.size() > 0)
1859 {
1860 monitor->m_pid = pid;
1861 // Let our process instance know the thread has stopped.
1862 monitor->SetState (StateType::eStateStopped);
1863 }
1864 else
1865 {
1866 args->m_error.SetErrorToGenericError();
1867 args->m_error.SetErrorString("No such process.");
1868 }
1869
1870 FINISH:
1871 return args->m_error.Success();
1872}
1873
Chaoren Lin97ccc292015-02-03 01:51:12 +00001874Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001875NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1876{
1877 long ptrace_opts = 0;
1878
1879 // Have the child raise an event on exit. This is used to keep the child in
1880 // limbo until it is destroyed.
1881 ptrace_opts |= PTRACE_O_TRACEEXIT;
1882
1883 // Have the tracer trace threads which spawn in the inferior process.
1884 // TODO: if we want to support tracing the inferiors' child, add the
1885 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1886 ptrace_opts |= PTRACE_O_TRACECLONE;
1887
1888 // Have the tracer notify us before execve returns
1889 // (needed to disable legacy SIGTRAP generation)
1890 ptrace_opts |= PTRACE_O_TRACEEXEC;
1891
Chaoren Lin97ccc292015-02-03 01:51:12 +00001892 Error error;
1893 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1894 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001895}
1896
1897static ExitType convert_pid_status_to_exit_type (int status)
1898{
1899 if (WIFEXITED (status))
1900 return ExitType::eExitTypeExit;
1901 else if (WIFSIGNALED (status))
1902 return ExitType::eExitTypeSignal;
1903 else if (WIFSTOPPED (status))
1904 return ExitType::eExitTypeStop;
1905 else
1906 {
1907 // We don't know what this is.
1908 return ExitType::eExitTypeInvalid;
1909 }
1910}
1911
1912static int convert_pid_status_to_return_code (int status)
1913{
1914 if (WIFEXITED (status))
1915 return WEXITSTATUS (status);
1916 else if (WIFSIGNALED (status))
1917 return WTERMSIG (status);
1918 else if (WIFSTOPPED (status))
1919 return WSTOPSIG (status);
1920 else
1921 {
1922 // We don't know what this is.
1923 return ExitType::eExitTypeInvalid;
1924 }
1925}
1926
1927// Main process monitoring waitpid-loop handler.
1928bool
1929NativeProcessLinux::MonitorCallback(void *callback_baton,
1930 lldb::pid_t pid,
1931 bool exited,
1932 int signal,
1933 int status)
1934{
1935 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1936
1937 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1938 assert (process && "process is null");
1939 if (!process)
1940 {
1941 if (log)
1942 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1943 return true;
1944 }
1945
1946 // Certain activities differ based on whether the pid is the tid of the main thread.
1947 const bool is_main_thread = (pid == process->GetID ());
1948
1949 // Assume we keep monitoring by default.
1950 bool stop_monitoring = false;
1951
1952 // Handle when the thread exits.
1953 if (exited)
1954 {
1955 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001956 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 +00001957
1958 // This is a thread that exited. Ensure we're not tracking it anymore.
1959 const bool thread_found = process->StopTrackingThread (pid);
1960
Chaoren Linfa03ad22015-02-03 01:50:42 +00001961 // Make sure the thread state coordinator knows about this.
1962 process->NotifyThreadDeath (pid);
1963
Todd Fialaaf245d12014-06-30 21:05:18 +00001964 if (is_main_thread)
1965 {
1966 // We only set the exit status and notify the delegate if we haven't already set the process
1967 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1968 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001969 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001970 if (!already_notified)
1971 {
1972 if (log)
1973 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 ()));
1974 // The main thread exited. We're done monitoring. Report to delegate.
1975 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1976
1977 // Notify delegate that our process has exited.
1978 process->SetState (StateType::eStateExited, true);
1979 }
1980 else
1981 {
1982 if (log)
1983 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1984 }
1985 return true;
1986 }
1987 else
1988 {
1989 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1990 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1991 // and we would have done an all-stop then.
1992 if (log)
1993 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1994
1995 // Not the main thread, we keep going.
1996 return false;
1997 }
1998 }
1999
2000 // Get details on the signal raised.
2001 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002002 const auto err = process->GetSignalInfo(pid, &info);
2003 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002004 {
2005 // We have retrieved the signal info. Dispatch appropriately.
2006 if (info.si_signo == SIGTRAP)
2007 process->MonitorSIGTRAP(&info, pid);
2008 else
2009 process->MonitorSignal(&info, pid, exited);
2010
2011 stop_monitoring = false;
2012 }
2013 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002014 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002015 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002016 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002017 // This is a group stop reception for this tid.
2018 if (log)
2019 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2020 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002021 }
2022 else
2023 {
2024 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2025
2026 // A return value of ESRCH means the thread/process is no longer on the system,
2027 // so it was killed somehow outside of our control. Either way, we can't do anything
2028 // with it anymore.
2029
2030 // We stop monitoring if it was the main thread.
2031 stop_monitoring = is_main_thread;
2032
2033 // Stop tracking the metadata for the thread since it's entirely off the system now.
2034 const bool thread_found = process->StopTrackingThread (pid);
2035
Chaoren Linfa03ad22015-02-03 01:50:42 +00002036 // Make sure the thread state coordinator knows about this.
2037 process->NotifyThreadDeath (pid);
2038
Todd Fialaaf245d12014-06-30 21:05:18 +00002039 if (log)
2040 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002041 __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 +00002042
2043 if (is_main_thread)
2044 {
2045 // Notify the delegate - our process is not available but appears to have been killed outside
2046 // our control. Is eStateExited the right exit state in this case?
2047 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2048 process->SetState (StateType::eStateExited, true);
2049 }
2050 else
2051 {
2052 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2053 if (log)
2054 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);
2055 }
2056 }
2057 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002058
2059 return stop_monitoring;
2060}
2061
2062void
2063NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2064{
2065 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2066 const bool is_main_thread = (pid == GetID ());
2067
2068 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2069 if (!info)
2070 return;
2071
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002072 Mutex::Locker locker (m_threads_mutex);
2073
Todd Fialaaf245d12014-06-30 21:05:18 +00002074 // See if we can find a thread for this signal.
2075 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2076 if (!thread_sp)
2077 {
2078 if (log)
2079 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2080 }
2081
2082 switch (info->si_code)
2083 {
2084 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2085 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2086 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2087
2088 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2089 {
2090 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2091
Chaoren Linfa03ad22015-02-03 01:50:42 +00002092 // The main thread is stopped here.
2093 if (thread_sp)
2094 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2095 NotifyThreadStop (pid);
2096
Todd Fialaaf245d12014-06-30 21:05:18 +00002097 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002098 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002099 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002100 tid = static_cast<lldb::tid_t> (event_message);
2101 if (log)
2102 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002103
Chaoren Linfa03ad22015-02-03 01:50:42 +00002104 // If we don't track the thread yet: create it, mark as stopped.
2105 // If we do track it, this is the wait we needed. Now resume the new thread.
2106 // In all cases, resume the current (i.e. main process) thread.
2107 bool created_now = false;
2108 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2109 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2110
2111 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2112 if (!created_now)
2113 {
2114 // We can now resume the newly created thread since it is fully created.
2115 NotifyThreadCreateStopped (tid);
2116 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002117 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002118 {
2119 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002120 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002121 },
2122 CoordinatorErrorHandler);
2123 }
2124 else
2125 {
2126 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2127 // this thread is ready to go.
2128 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetLaunching ();
2129 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002130 }
2131 else
2132 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002133 if (log)
2134 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 +00002135 }
2136
2137 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002138 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002139 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002140 {
2141 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002142 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002143 },
2144 CoordinatorErrorHandler);
2145
Todd Fialaaf245d12014-06-30 21:05:18 +00002146 break;
2147 }
2148
2149 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002150 {
2151 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002152 if (log)
2153 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002154
Chaoren Linfa03ad22015-02-03 01:50:42 +00002155 // The thread state coordinator needs to reset due to the exec.
2156 m_coordinator_up->ResetForExec ();
2157
2158 // 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 +00002159 if (log)
2160 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2161
2162 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002163 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002164 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2165 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002166 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002167 main_thread_sp = thread_sp;
2168 if (log)
2169 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002170 }
2171 else
2172 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002173 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002174 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002175 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002176 }
2177 }
2178
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002179 m_threads.clear ();
2180
2181 if (main_thread_sp)
2182 {
2183 m_threads.push_back (main_thread_sp);
2184 SetCurrentThreadID (main_thread_sp->GetID ());
2185 reinterpret_cast<NativeThreadLinux*>(main_thread_sp.get())->SetStoppedByExec ();
2186 }
2187 else
2188 {
2189 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2190 if (log)
2191 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2192 }
2193
Chaoren Linfa03ad22015-02-03 01:50:42 +00002194 // Tell coordinator about about the "new" (since exec) stopped main thread.
2195 const lldb::tid_t main_thread_tid = GetID ();
2196 NotifyThreadCreateStopped (main_thread_tid);
2197
2198 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2199 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002200 // Let our delegate know we have just exec'd.
2201 NotifyDidExec ();
2202
2203 // If we have a main thread, indicate we are stopped.
2204 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002205
2206 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002207 CallAfterRunningThreadsStop (pid,
2208 [=] (lldb::tid_t signaling_tid)
2209 {
2210 SetState (StateType::eStateStopped, true);
2211 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002212
Todd Fialaaf245d12014-06-30 21:05:18 +00002213 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002214 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002215
2216 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2217 {
2218 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002219
2220 // This thread is currently stopped. It's not actually dead yet, just about to be.
2221 NotifyThreadStop (pid);
2222
Todd Fialaaf245d12014-06-30 21:05:18 +00002223 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002224 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002225 data = -1;
2226
2227 if (log)
2228 {
2229 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2230 __FUNCTION__,
2231 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2232 pid,
2233 is_main_thread ? "is main thread" : "not main thread");
2234 }
2235
Todd Fialaaf245d12014-06-30 21:05:18 +00002236 if (is_main_thread)
2237 {
2238 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002239 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002240
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002241 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002242 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002243 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002244 {
2245 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002246 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002247 },
2248 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002249
2250 break;
2251 }
2252
2253 case 0:
2254 case TRAP_TRACE:
2255 // We receive this on single stepping.
2256 if (log)
2257 log->Printf ("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", __FUNCTION__, pid);
2258
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002259 if (thread_sp)
2260 {
Chaoren Lin28e57422015-02-03 01:51:25 +00002261 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByTrace ();
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002262 }
2263
Chaoren Linfa03ad22015-02-03 01:50:42 +00002264 // This thread is currently stopped.
2265 NotifyThreadStop (pid);
2266
Chaoren Linae29d392015-02-03 01:50:46 +00002267 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2268 // This would have already happened at the time the Resume() with step operation was signaled.
2269 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2270 // once all running threads have checked in as stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002271 SetCurrentThreadID (pid);
2272 // Tell the process we have a stop (from software breakpoint).
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002273 CallAfterRunningThreadsStop (pid,
2274 [=] (lldb::tid_t signaling_tid)
2275 {
2276 SetState (StateType::eStateStopped, true);
2277 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002278 break;
2279
2280 case SI_KERNEL:
2281 case TRAP_BRKPT:
2282 if (log)
2283 log->Printf ("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2284
Chaoren Linfa03ad22015-02-03 01:50:42 +00002285 // This thread is currently stopped.
2286 NotifyThreadStop (pid);
2287
Todd Fialaaf245d12014-06-30 21:05:18 +00002288 // Mark the thread as stopped at breakpoint.
2289 if (thread_sp)
2290 {
Chaoren Lin28e57422015-02-03 01:51:25 +00002291 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByBreakpoint ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002292 Error error = FixupBreakpointPCAsNeeded (thread_sp);
2293 if (error.Fail ())
2294 {
2295 if (log)
2296 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", __FUNCTION__, pid, error.AsCString ());
2297 }
2298 }
2299 else
2300 {
2301 if (log)
2302 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": warning, cannot process software breakpoint since no thread metadata", __FUNCTION__, pid);
2303 }
2304
2305
Chaoren Linfa03ad22015-02-03 01:50:42 +00002306 // We need to tell all other running threads before we notify the delegate about this stop.
2307 CallAfterRunningThreadsStop (pid,
2308 [=](lldb::tid_t deferred_notification_tid)
2309 {
2310 SetCurrentThreadID (deferred_notification_tid);
2311 // Tell the process we have a stop (from software breakpoint).
2312 SetState (StateType::eStateStopped, true);
2313 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002314 break;
2315
2316 case TRAP_HWBKPT:
2317 if (log)
2318 log->Printf ("NativeProcessLinux::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2319
Chaoren Linfa03ad22015-02-03 01:50:42 +00002320 // This thread is currently stopped.
2321 NotifyThreadStop (pid);
2322
Todd Fialaaf245d12014-06-30 21:05:18 +00002323 // Mark the thread as stopped at watchpoint.
2324 // The address is at (lldb::addr_t)info->si_addr if we need it.
2325 if (thread_sp)
Chaoren Lin18fe6402015-02-03 01:51:47 +00002326 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedByWatchpoint ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002327 else
2328 {
2329 if (log)
2330 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ": warning, cannot process hardware breakpoint since no thread metadata", __FUNCTION__, GetID (), pid);
2331 }
2332
Chaoren Linfa03ad22015-02-03 01:50:42 +00002333 // We need to tell all other running threads before we notify the delegate about this stop.
2334 CallAfterRunningThreadsStop (pid,
2335 [=](lldb::tid_t deferred_notification_tid)
2336 {
2337 SetCurrentThreadID (deferred_notification_tid);
2338 // Tell the process we have a stop (from hardware breakpoint).
2339 SetState (StateType::eStateStopped, true);
2340 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002341 break;
2342
2343 case SIGTRAP:
2344 case (SIGTRAP | 0x80):
2345 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002346 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2347
2348 // This thread is currently stopped.
2349 NotifyThreadStop (pid);
2350 if (thread_sp)
2351 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2352
2353
Todd Fialaaf245d12014-06-30 21:05:18 +00002354 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002355 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002356 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002357 {
2358 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002359 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002360 },
2361 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002362 break;
2363
2364 default:
2365 assert(false && "Unexpected SIGTRAP code!");
2366 if (log)
2367 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)));
2368 break;
2369
2370 }
2371}
2372
2373void
2374NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2375{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002376 assert (info && "null info");
2377 if (!info)
2378 return;
2379
2380 const int signo = info->si_signo;
2381 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002382
2383 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2384
2385 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2386 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2387 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2388 //
2389 // IOW, user generated signals never generate what we consider to be a
2390 // "crash".
2391 //
2392 // Similarly, ACK signals generated by this monitor.
2393
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002394 Mutex::Locker locker (m_threads_mutex);
2395
Todd Fialaaf245d12014-06-30 21:05:18 +00002396 // See if we can find a thread for this signal.
2397 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2398 if (!thread_sp)
2399 {
2400 if (log)
2401 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2402 }
2403
2404 // Handle the signal.
2405 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2406 {
2407 if (log)
2408 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2409 __FUNCTION__,
2410 GetUnixSignals ().GetSignalAsCString (signo),
2411 signo,
2412 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2413 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002414 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002415 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002416 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002417
Todd Fiala58a2f662014-08-12 17:02:07 +00002418 // Check for new thread notification.
2419 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2420 {
2421 // A new thread creation is being signaled. This is one of two parts that come in
2422 // a non-deterministic order. pid is the thread id.
2423 if (log)
2424 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2425 __FUNCTION__, GetID (), pid);
2426
2427 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002428 bool created_now = false;
2429 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002430 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2431
2432 // 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 +00002433 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002434 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002435 // We can now resume the newly created thread since it is fully created.
2436 NotifyThreadCreateStopped (pid);
2437 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002438 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002439 {
2440 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002441 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002442 },
2443 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002444 }
2445 else
2446 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002447 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2448 // this thread is ready to go.
2449 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002450 }
2451
Todd Fiala58a2f662014-08-12 17:02:07 +00002452 // Done handling.
2453 return;
2454 }
2455
2456 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002457 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002458 {
2459 // This is a tgkill()-based stop.
2460 if (thread_sp)
2461 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002462 if (log)
2463 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2464 __FUNCTION__,
2465 GetID (),
2466 pid);
2467
Chaoren Linaab58632015-02-03 01:50:57 +00002468 // Check that we're not already marked with a stop reason.
2469 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2470 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2471 // and that, without an intervening resume, we received another stop. It is more likely
2472 // that we are missing the marking of a run state somewhere if we find that the thread was
2473 // marked as stopped.
2474 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ());
2475 assert (linux_thread_p && "linux_thread_p is null!");
2476
2477 const StateType thread_state = linux_thread_p->GetState ();
2478 if (!StateIsStoppedState (thread_state, false))
2479 {
2480 // An inferior thread just stopped, but was not the primary cause of the process stop.
2481 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2482 // stop signal as 0 to let lldb know this isn't the important stop.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002483 linux_thread_p->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002484 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002485 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002486 }
2487 else
2488 {
2489 if (log)
2490 {
2491 // Retrieve the signal name if the thread was stopped by a signal.
2492 int stop_signo = 0;
2493 const bool stopped_by_signal = linux_thread_p->IsStopped (&stop_signo);
2494 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2495 if (!signal_name)
2496 signal_name = "<no-signal-name>";
2497
2498 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",
2499 __FUNCTION__,
2500 GetID (),
2501 linux_thread_p->GetID (),
2502 StateAsCString (thread_state),
2503 stop_signo,
2504 signal_name);
2505 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002506 // Tell the thread state coordinator about the stop.
2507 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002508 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002509 }
2510
2511 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002512 return;
2513 }
2514
2515 if (log)
2516 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2517
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002518 // This thread is stopped.
2519 NotifyThreadStop (pid);
2520
Todd Fialaaf245d12014-06-30 21:05:18 +00002521 switch (signo)
2522 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002523 case SIGSTOP:
2524 {
2525 if (log)
2526 {
2527 if (is_from_llgs)
2528 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2529 else
2530 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2531 }
2532
Chaoren Linfa03ad22015-02-03 01:50:42 +00002533 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2534 // This thread will get stopped again as part of the group-stop completion.
2535 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002536 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002537 {
2538 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2539 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002540 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002541 },
2542 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002543 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002544 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002545 case SIGSEGV:
2546 case SIGILL:
2547 case SIGFPE:
2548 case SIGBUS:
2549 if (thread_sp)
Chaoren Lin28e57422015-02-03 01:51:25 +00002550 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002551 break;
2552 default:
2553 // This is just a pre-signal-delivery notification of the incoming signal.
2554 if (thread_sp)
2555 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2556
2557 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002558 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002559
2560 // Send a stop to the debugger after we get all other threads to stop.
2561 CallAfterRunningThreadsStop (pid,
2562 [=] (lldb::tid_t signaling_tid)
2563 {
2564 SetCurrentThreadID (signaling_tid);
2565 SetState (StateType::eStateStopped, true);
2566 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002567}
2568
2569Error
2570NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2571{
Todd Fialaaf245d12014-06-30 21:05:18 +00002572 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2573 if (log)
2574 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2575
Chaoren Lin03f12d62015-02-03 01:50:49 +00002576 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2577 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002578 int deferred_signo = 0;
2579 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002580 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002581
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002582 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002583
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002584 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002585 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002586 assert (thread_sp && "thread list should not contain NULL threads");
2587
2588 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2589
2590 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002591 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002592 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002593 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2594 __FUNCTION__, GetID (), thread_sp->GetID ());
2595 continue;
2596 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002597
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002598 if (log)
2599 {
2600 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2601 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2602 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002603
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002604 switch (action->state)
2605 {
2606 case eStateRunning:
2607 {
2608 // Run the thread, possibly feeding it the signal.
2609 const int signo = action->signal;
2610 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2611 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2612 {
2613 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2614 // Pass this signal number on to the inferior to handle.
2615 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2616 if (resume_result.Success())
2617 SetState(eStateRunning, true);
2618 return resume_result;
2619 },
2620 CoordinatorErrorHandler);
2621 break;
2622 }
2623
2624 case eStateStepping:
2625 {
2626 // Request the step.
2627 const int signo = action->signal;
2628 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2629 [=](lldb::tid_t tid_to_step, bool supress_signal)
2630 {
2631 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStepping ();
2632 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2633 assert (step_result.Success() && "SingleStep() failed");
2634 if (step_result.Success())
2635 SetState(eStateStepping, true);
2636 return step_result;
2637 },
2638 CoordinatorErrorHandler);
2639 stepping = true;
2640 break;
2641 }
2642
2643 case eStateSuspended:
2644 case eStateStopped:
2645 // if we haven't chosen a deferred signal tid yet, use this one.
2646 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002647 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002648 deferred_signal_tid = thread_sp->GetID ();
2649 deferred_signal_thread_sp = thread_sp;
2650 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002651 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002652 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002653
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002654 default:
2655 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2656 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002657 }
2658 }
2659
Chaoren Linfa03ad22015-02-03 01:50:42 +00002660 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2661 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002662 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2663 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002664 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002665 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2666 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002667 [=](lldb::tid_t deferred_notification_tid)
2668 {
Chaoren Linae29d392015-02-03 01:50:46 +00002669 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002670 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002671
2672 // Set the thread state as stopped by the deferred signo.
2673 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (deferred_signo);
2674
2675 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002676 SetState (StateType::eStateStopped, true);
2677 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002678 }
2679
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002680 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002681}
2682
2683Error
2684NativeProcessLinux::Halt ()
2685{
2686 Error error;
2687
Todd Fialaaf245d12014-06-30 21:05:18 +00002688 if (kill (GetID (), SIGSTOP) != 0)
2689 error.SetErrorToErrno ();
2690
2691 return error;
2692}
2693
2694Error
2695NativeProcessLinux::Detach ()
2696{
2697 Error error;
2698
2699 // Tell ptrace to detach from the process.
2700 if (GetID () != LLDB_INVALID_PROCESS_ID)
2701 error = Detach (GetID ());
2702
2703 // Stop monitoring the inferior.
2704 StopMonitor ();
2705
2706 // No error.
2707 return error;
2708}
2709
2710Error
2711NativeProcessLinux::Signal (int signo)
2712{
2713 Error error;
2714
2715 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2716 if (log)
2717 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2718 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2719
2720 if (kill(GetID(), signo))
2721 error.SetErrorToErrno();
2722
2723 return error;
2724}
2725
2726Error
Chaoren Line9547b82015-02-03 01:51:00 +00002727NativeProcessLinux::Interrupt ()
2728{
2729 // Pick a running thread (or if none, a not-dead stopped thread) as
2730 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002731 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2732
2733 NativeThreadProtocolSP running_thread_sp;
2734 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002735
2736 if (log)
2737 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2738
2739 Mutex::Locker locker (m_threads_mutex);
2740
2741 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002742 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002743 // The thread shouldn't be null but lets just cover that here.
2744 if (!thread_sp)
2745 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002746
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002747 // If we have a running or stepping thread, we'll call that the
2748 // target of the interrupt.
2749 const auto thread_state = thread_sp->GetState ();
2750 if (thread_state == eStateRunning ||
2751 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002752 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002753 running_thread_sp = thread_sp;
2754 break;
2755 }
2756 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2757 {
2758 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2759 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002760 }
2761 }
2762
2763 if (!running_thread_sp && !stopped_thread_sp)
2764 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002765 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002766 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002767 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002768
Chaoren Line9547b82015-02-03 01:51:00 +00002769 return error;
2770 }
2771
2772 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2773
2774 if (log)
2775 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2776 __FUNCTION__,
2777 GetID (),
2778 running_thread_sp ? "running" : "stopped",
2779 deferred_signal_thread_sp->GetID ());
2780
2781 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2782 [=](lldb::tid_t deferred_notification_tid)
2783 {
2784 // Set the signal thread to the current thread.
2785 SetCurrentThreadID (deferred_notification_tid);
2786
2787 // Set the thread state as stopped by the deferred signo.
2788 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
2789
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002790 // Tell the process delegate that the process is in a stopped state.
2791 SetState (StateType::eStateStopped, true);
2792 });
2793 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002794}
2795
2796Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002797NativeProcessLinux::Kill ()
2798{
2799 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2800 if (log)
2801 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2802
2803 Error error;
2804
2805 switch (m_state)
2806 {
2807 case StateType::eStateInvalid:
2808 case StateType::eStateExited:
2809 case StateType::eStateCrashed:
2810 case StateType::eStateDetached:
2811 case StateType::eStateUnloaded:
2812 // Nothing to do - the process is already dead.
2813 if (log)
2814 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2815 return error;
2816
2817 case StateType::eStateConnected:
2818 case StateType::eStateAttaching:
2819 case StateType::eStateLaunching:
2820 case StateType::eStateStopped:
2821 case StateType::eStateRunning:
2822 case StateType::eStateStepping:
2823 case StateType::eStateSuspended:
2824 // We can try to kill a process in these states.
2825 break;
2826 }
2827
2828 if (kill (GetID (), SIGKILL) != 0)
2829 {
2830 error.SetErrorToErrno ();
2831 return error;
2832 }
2833
2834 return error;
2835}
2836
2837static Error
2838ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2839{
2840 memory_region_info.Clear();
2841
2842 StringExtractor line_extractor (maps_line.c_str ());
2843
2844 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2845 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2846
2847 // Parse out the starting address
2848 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2849
2850 // Parse out hyphen separating start and end address from range.
2851 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2852 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2853
2854 // Parse out the ending address
2855 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2856
2857 // Parse out the space after the address.
2858 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2859 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2860
2861 // Save the range.
2862 memory_region_info.GetRange ().SetRangeBase (start_address);
2863 memory_region_info.GetRange ().SetRangeEnd (end_address);
2864
2865 // Parse out each permission entry.
2866 if (line_extractor.GetBytesLeft () < 4)
2867 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2868
2869 // Handle read permission.
2870 const char read_perm_char = line_extractor.GetChar ();
2871 if (read_perm_char == 'r')
2872 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2873 else
2874 {
2875 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2876 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2877 }
2878
2879 // Handle write permission.
2880 const char write_perm_char = line_extractor.GetChar ();
2881 if (write_perm_char == 'w')
2882 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2883 else
2884 {
2885 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2886 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2887 }
2888
2889 // Handle execute permission.
2890 const char exec_perm_char = line_extractor.GetChar ();
2891 if (exec_perm_char == 'x')
2892 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2893 else
2894 {
2895 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2896 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2897 }
2898
2899 return Error ();
2900}
2901
2902Error
2903NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2904{
2905 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2906 // with no perms if it is not mapped.
2907
2908 // Use an approach that reads memory regions from /proc/{pid}/maps.
2909 // Assume proc maps entries are in ascending order.
2910 // FIXME assert if we find differently.
2911 Mutex::Locker locker (m_mem_region_cache_mutex);
2912
2913 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2914 Error error;
2915
2916 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2917 {
2918 // We're done.
2919 error.SetErrorString ("unsupported");
2920 return error;
2921 }
2922
2923 // If our cache is empty, pull the latest. There should always be at least one memory region
2924 // if memory region handling is supported.
2925 if (m_mem_region_cache.empty ())
2926 {
2927 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2928 [&] (const std::string &line) -> bool
2929 {
2930 MemoryRegionInfo info;
2931 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2932 if (parse_error.Success ())
2933 {
2934 m_mem_region_cache.push_back (info);
2935 return true;
2936 }
2937 else
2938 {
2939 if (log)
2940 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2941 return false;
2942 }
2943 });
2944
2945 // If we had an error, we'll mark unsupported.
2946 if (error.Fail ())
2947 {
2948 m_supports_mem_region = LazyBool::eLazyBoolNo;
2949 return error;
2950 }
2951 else if (m_mem_region_cache.empty ())
2952 {
2953 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2954 // is supported. Assume we don't support map entries via procfs.
2955 if (log)
2956 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2957 m_supports_mem_region = LazyBool::eLazyBoolNo;
2958 error.SetErrorString ("not supported");
2959 return error;
2960 }
2961
2962 if (log)
2963 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2964
2965 // We support memory retrieval, remember that.
2966 m_supports_mem_region = LazyBool::eLazyBoolYes;
2967 }
2968 else
2969 {
2970 if (log)
2971 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2972 }
2973
2974 lldb::addr_t prev_base_address = 0;
2975
2976 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2977 // There can be a ton of regions on pthreads apps with lots of threads.
2978 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2979 {
2980 MemoryRegionInfo &proc_entry_info = *it;
2981
2982 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2983 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2984 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2985
2986 // If the target address comes before this entry, indicate distance to next region.
2987 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2988 {
2989 range_info.GetRange ().SetRangeBase (load_addr);
2990 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2991 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2992 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2993 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2994
2995 return error;
2996 }
2997 else if (proc_entry_info.GetRange ().Contains (load_addr))
2998 {
2999 // The target address is within the memory region we're processing here.
3000 range_info = proc_entry_info;
3001 return error;
3002 }
3003
3004 // The target memory address comes somewhere after the region we just parsed.
3005 }
3006
3007 // If we made it here, we didn't find an entry that contained the given address.
3008 error.SetErrorString ("address comes after final region");
3009
3010 if (log)
3011 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3012
3013 return error;
3014}
3015
3016void
3017NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3018{
3019 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3020 if (log)
3021 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3022
3023 {
3024 Mutex::Locker locker (m_mem_region_cache_mutex);
3025 if (log)
3026 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3027 m_mem_region_cache.clear ();
3028 }
3029}
3030
3031Error
3032NativeProcessLinux::AllocateMemory (
3033 lldb::addr_t size,
3034 uint32_t permissions,
3035 lldb::addr_t &addr)
3036{
3037 // FIXME implementing this requires the equivalent of
3038 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3039 // functional ThreadPlans working with Native*Protocol.
3040#if 1
3041 return Error ("not implemented yet");
3042#else
3043 addr = LLDB_INVALID_ADDRESS;
3044
3045 unsigned prot = 0;
3046 if (permissions & lldb::ePermissionsReadable)
3047 prot |= eMmapProtRead;
3048 if (permissions & lldb::ePermissionsWritable)
3049 prot |= eMmapProtWrite;
3050 if (permissions & lldb::ePermissionsExecutable)
3051 prot |= eMmapProtExec;
3052
3053 // TODO implement this directly in NativeProcessLinux
3054 // (and lift to NativeProcessPOSIX if/when that class is
3055 // refactored out).
3056 if (InferiorCallMmap(this, addr, 0, size, prot,
3057 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3058 m_addr_to_mmap_size[addr] = size;
3059 return Error ();
3060 } else {
3061 addr = LLDB_INVALID_ADDRESS;
3062 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3063 }
3064#endif
3065}
3066
3067Error
3068NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3069{
3070 // FIXME see comments in AllocateMemory - required lower-level
3071 // bits not in place yet (ThreadPlans)
3072 return Error ("not implemented");
3073}
3074
3075lldb::addr_t
3076NativeProcessLinux::GetSharedLibraryInfoAddress ()
3077{
3078#if 1
3079 // punt on this for now
3080 return LLDB_INVALID_ADDRESS;
3081#else
3082 // Return the image info address for the exe module
3083#if 1
3084 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3085
3086 ModuleSP module_sp;
3087 Error error = GetExeModuleSP (module_sp);
3088 if (error.Fail ())
3089 {
3090 if (log)
3091 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3092 return LLDB_INVALID_ADDRESS;
3093 }
3094
3095 if (module_sp == nullptr)
3096 {
3097 if (log)
3098 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3099 return LLDB_INVALID_ADDRESS;
3100 }
3101
3102 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3103 if (object_file_sp == nullptr)
3104 {
3105 if (log)
3106 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3107 return LLDB_INVALID_ADDRESS;
3108 }
3109
3110 return obj_file_sp->GetImageInfoAddress();
3111#else
3112 Target *target = &GetTarget();
3113 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3114 Address addr = obj_file->GetImageInfoAddress(target);
3115
3116 if (addr.IsValid())
3117 return addr.GetLoadAddress(target);
3118 return LLDB_INVALID_ADDRESS;
3119#endif
3120#endif // punt on this for now
3121}
3122
3123size_t
3124NativeProcessLinux::UpdateThreads ()
3125{
3126 // The NativeProcessLinux monitoring threads are always up to date
3127 // with respect to thread state and they keep the thread list
3128 // populated properly. All this method needs to do is return the
3129 // thread count.
3130 Mutex::Locker locker (m_threads_mutex);
3131 return m_threads.size ();
3132}
3133
3134bool
3135NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3136{
3137 arch = m_arch;
3138 return true;
3139}
3140
3141Error
3142NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3143{
3144 // FIXME put this behind a breakpoint protocol class that can be
3145 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003146 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003147 static const uint8_t g_i386_opcode [] = { 0xCC };
3148
3149 switch (m_arch.GetMachine ())
3150 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003151 case llvm::Triple::aarch64:
3152 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3153 return Error ();
3154
Todd Fialaaf245d12014-06-30 21:05:18 +00003155 case llvm::Triple::x86:
3156 case llvm::Triple::x86_64:
3157 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3158 return Error ();
3159
3160 default:
3161 assert(false && "CPU type not supported!");
3162 return Error ("CPU type not supported");
3163 }
3164}
3165
3166Error
3167NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3168{
3169 if (hardware)
3170 return Error ("NativeProcessLinux does not support hardware breakpoints");
3171 else
3172 return SetSoftwareBreakpoint (addr, size);
3173}
3174
3175Error
3176NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3177{
3178 // FIXME put this behind a breakpoint protocol class that can be
3179 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003180 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003181 static const uint8_t g_i386_opcode [] = { 0xCC };
3182
3183 switch (m_arch.GetMachine ())
3184 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003185 case llvm::Triple::aarch64:
3186 trap_opcode_bytes = g_aarch64_opcode;
3187 actual_opcode_size = sizeof(g_aarch64_opcode);
3188 return Error ();
3189
Todd Fialaaf245d12014-06-30 21:05:18 +00003190 case llvm::Triple::x86:
3191 case llvm::Triple::x86_64:
3192 trap_opcode_bytes = g_i386_opcode;
3193 actual_opcode_size = sizeof(g_i386_opcode);
3194 return Error ();
3195
3196 default:
3197 assert(false && "CPU type not supported!");
3198 return Error ("CPU type not supported");
3199 }
3200}
3201
3202#if 0
3203ProcessMessage::CrashReason
3204NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3205{
3206 ProcessMessage::CrashReason reason;
3207 assert(info->si_signo == SIGSEGV);
3208
3209 reason = ProcessMessage::eInvalidCrashReason;
3210
3211 switch (info->si_code)
3212 {
3213 default:
3214 assert(false && "unexpected si_code for SIGSEGV");
3215 break;
3216 case SI_KERNEL:
3217 // Linux will occasionally send spurious SI_KERNEL codes.
3218 // (this is poorly documented in sigaction)
3219 // One way to get this is via unaligned SIMD loads.
3220 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3221 break;
3222 case SEGV_MAPERR:
3223 reason = ProcessMessage::eInvalidAddress;
3224 break;
3225 case SEGV_ACCERR:
3226 reason = ProcessMessage::ePrivilegedAddress;
3227 break;
3228 }
3229
3230 return reason;
3231}
3232#endif
3233
3234
3235#if 0
3236ProcessMessage::CrashReason
3237NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3238{
3239 ProcessMessage::CrashReason reason;
3240 assert(info->si_signo == SIGILL);
3241
3242 reason = ProcessMessage::eInvalidCrashReason;
3243
3244 switch (info->si_code)
3245 {
3246 default:
3247 assert(false && "unexpected si_code for SIGILL");
3248 break;
3249 case ILL_ILLOPC:
3250 reason = ProcessMessage::eIllegalOpcode;
3251 break;
3252 case ILL_ILLOPN:
3253 reason = ProcessMessage::eIllegalOperand;
3254 break;
3255 case ILL_ILLADR:
3256 reason = ProcessMessage::eIllegalAddressingMode;
3257 break;
3258 case ILL_ILLTRP:
3259 reason = ProcessMessage::eIllegalTrap;
3260 break;
3261 case ILL_PRVOPC:
3262 reason = ProcessMessage::ePrivilegedOpcode;
3263 break;
3264 case ILL_PRVREG:
3265 reason = ProcessMessage::ePrivilegedRegister;
3266 break;
3267 case ILL_COPROC:
3268 reason = ProcessMessage::eCoprocessorError;
3269 break;
3270 case ILL_BADSTK:
3271 reason = ProcessMessage::eInternalStackError;
3272 break;
3273 }
3274
3275 return reason;
3276}
3277#endif
3278
3279#if 0
3280ProcessMessage::CrashReason
3281NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3282{
3283 ProcessMessage::CrashReason reason;
3284 assert(info->si_signo == SIGFPE);
3285
3286 reason = ProcessMessage::eInvalidCrashReason;
3287
3288 switch (info->si_code)
3289 {
3290 default:
3291 assert(false && "unexpected si_code for SIGFPE");
3292 break;
3293 case FPE_INTDIV:
3294 reason = ProcessMessage::eIntegerDivideByZero;
3295 break;
3296 case FPE_INTOVF:
3297 reason = ProcessMessage::eIntegerOverflow;
3298 break;
3299 case FPE_FLTDIV:
3300 reason = ProcessMessage::eFloatDivideByZero;
3301 break;
3302 case FPE_FLTOVF:
3303 reason = ProcessMessage::eFloatOverflow;
3304 break;
3305 case FPE_FLTUND:
3306 reason = ProcessMessage::eFloatUnderflow;
3307 break;
3308 case FPE_FLTRES:
3309 reason = ProcessMessage::eFloatInexactResult;
3310 break;
3311 case FPE_FLTINV:
3312 reason = ProcessMessage::eFloatInvalidOperation;
3313 break;
3314 case FPE_FLTSUB:
3315 reason = ProcessMessage::eFloatSubscriptRange;
3316 break;
3317 }
3318
3319 return reason;
3320}
3321#endif
3322
3323#if 0
3324ProcessMessage::CrashReason
3325NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3326{
3327 ProcessMessage::CrashReason reason;
3328 assert(info->si_signo == SIGBUS);
3329
3330 reason = ProcessMessage::eInvalidCrashReason;
3331
3332 switch (info->si_code)
3333 {
3334 default:
3335 assert(false && "unexpected si_code for SIGBUS");
3336 break;
3337 case BUS_ADRALN:
3338 reason = ProcessMessage::eIllegalAlignment;
3339 break;
3340 case BUS_ADRERR:
3341 reason = ProcessMessage::eIllegalAddress;
3342 break;
3343 case BUS_OBJERR:
3344 reason = ProcessMessage::eHardwareError;
3345 break;
3346 }
3347
3348 return reason;
3349}
3350#endif
3351
3352void
3353NativeProcessLinux::ServeOperation(OperationArgs *args)
3354{
3355 NativeProcessLinux *monitor = args->m_monitor;
3356
3357 // We are finised with the arguments and are ready to go. Sync with the
3358 // parent thread and start serving operations on the inferior.
3359 sem_post(&args->m_semaphore);
3360
3361 for(;;)
3362 {
3363 // wait for next pending operation
3364 if (sem_wait(&monitor->m_operation_pending))
3365 {
3366 if (errno == EINTR)
3367 continue;
3368 assert(false && "Unexpected errno from sem_wait");
3369 }
3370
3371 reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3372
3373 // notify calling thread that operation is complete
3374 sem_post(&monitor->m_operation_done);
3375 }
3376}
3377
3378void
3379NativeProcessLinux::DoOperation(void *op)
3380{
3381 Mutex::Locker lock(m_operation_mutex);
3382
3383 m_operation = op;
3384
3385 // notify operation thread that an operation is ready to be processed
3386 sem_post(&m_operation_pending);
3387
3388 // wait for operation to complete
3389 while (sem_wait(&m_operation_done))
3390 {
3391 if (errno == EINTR)
3392 continue;
3393 assert(false && "Unexpected errno from sem_wait");
3394 }
3395}
3396
3397Error
3398NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3399{
3400 ReadOperation op(addr, buf, size, bytes_read);
3401 DoOperation(&op);
3402 return op.GetError ();
3403}
3404
3405Error
3406NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3407{
3408 WriteOperation op(addr, buf, size, bytes_written);
3409 DoOperation(&op);
3410 return op.GetError ();
3411}
3412
Chaoren Lin97ccc292015-02-03 01:51:12 +00003413Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003414NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3415 uint32_t size, RegisterValue &value)
3416{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003417 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003418 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003419 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003420}
3421
Chaoren Lin97ccc292015-02-03 01:51:12 +00003422Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003423NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3424 const char* reg_name, const RegisterValue &value)
3425{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003426 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003427 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003428 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003429}
3430
Chaoren Lin97ccc292015-02-03 01:51:12 +00003431Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003432NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3433{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003434 ReadGPROperation op(tid, buf, buf_size);
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::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3441{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003442 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003443 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003444 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003445}
3446
Chaoren Lin97ccc292015-02-03 01:51:12 +00003447Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003448NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3449{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003450 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003451 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003452 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003453}
3454
Chaoren Lin97ccc292015-02-03 01:51:12 +00003455Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003456NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3457{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003458 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003459 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003460 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003461}
3462
Chaoren Lin97ccc292015-02-03 01:51:12 +00003463Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003464NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3465{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003466 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003467 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003468 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003469}
3470
Chaoren Lin97ccc292015-02-03 01:51:12 +00003471Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003472NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3473{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003474 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003475 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003476 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003477}
3478
Chaoren Lin97ccc292015-02-03 01:51:12 +00003479Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003480NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3481{
Todd Fialaaf245d12014-06-30 21:05:18 +00003482 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3483
3484 if (log)
3485 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3486 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003487 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003488 DoOperation (&op);
3489 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003490 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3491 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003492}
3493
Chaoren Lin97ccc292015-02-03 01:51:12 +00003494Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003495NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3496{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003497 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003498 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003499 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003500}
3501
Chaoren Lin97ccc292015-02-03 01:51:12 +00003502Error
3503NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003504{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003505 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003506 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003507 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003508}
3509
Chaoren Lin97ccc292015-02-03 01:51:12 +00003510Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003511NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3512{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003513 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003514 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003515 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003516}
3517
3518lldb_private::Error
3519NativeProcessLinux::Detach(lldb::tid_t tid)
3520{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003521 if (tid == LLDB_INVALID_THREAD_ID)
3522 return Error();
3523
3524 DetachOperation op(tid);
3525 DoOperation(&op);
3526 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003527}
3528
3529bool
3530NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3531{
3532 int target_fd = open(path, flags, 0666);
3533
3534 if (target_fd == -1)
3535 return false;
3536
Pavel Labath493c3a12015-02-04 10:36:57 +00003537 if (dup2(target_fd, fd) == -1)
3538 return false;
3539
3540 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003541}
3542
3543void
3544NativeProcessLinux::StopMonitoringChildProcess()
3545{
Zachary Turneracee96a2014-09-23 18:32:09 +00003546 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003547 {
Zachary Turner39de3112014-09-09 20:54:56 +00003548 m_monitor_thread.Cancel();
3549 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003550 }
3551}
3552
3553void
3554NativeProcessLinux::StopMonitor()
3555{
3556 StopMonitoringChildProcess();
3557 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003558 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003559 sem_destroy(&m_operation_pending);
3560 sem_destroy(&m_operation_done);
3561
3562 // TODO: validate whether this still holds, fix up comment.
3563 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3564 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3565 // the descriptor to a ConnectionFileDescriptor object. Consequently
3566 // even though still has the file descriptor, we shouldn't close it here.
3567}
3568
3569void
3570NativeProcessLinux::StopOpThread()
3571{
Zachary Turneracee96a2014-09-23 18:32:09 +00003572 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003573 return;
3574
Zachary Turner39de3112014-09-09 20:54:56 +00003575 m_operation_thread.Cancel();
3576 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003577}
3578
Chaoren Linfa03ad22015-02-03 01:50:42 +00003579Error
3580NativeProcessLinux::StartCoordinatorThread ()
3581{
3582 Error error;
3583 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3584 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3585
3586 // Skip if thread is already running
3587 if (m_coordinator_thread.IsJoinable())
3588 {
3589 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3590 if (log)
3591 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3592 return error;
3593 }
3594
3595 // Enable verbose logging if lldb thread logging is enabled.
3596 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3597
3598 if (log)
3599 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3600 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3601 return error;
3602}
3603
3604void *
3605NativeProcessLinux::CoordinatorThread (void *arg)
3606{
3607 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3608
3609 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3610 assert (process && "null process passed to CoordinatorThread");
3611 if (!process)
3612 {
3613 if (log)
3614 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3615 return nullptr;
3616 }
3617
3618 // Run the thread state coordinator loop until it is done. This call uses
3619 // efficient waiting for an event to be ready.
3620 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3621 {
3622 }
3623
3624 if (log)
3625 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3626
3627 return nullptr;
3628}
3629
3630void
3631NativeProcessLinux::StopCoordinatorThread()
3632{
3633 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3634 if (log)
3635 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3636
3637 // Tell the coordinator we're done. This will cause the coordinator
3638 // run loop thread to exit when the processing queue hits this message.
3639 m_coordinator_up->StopCoordinator ();
3640}
3641
Todd Fialaaf245d12014-06-30 21:05:18 +00003642bool
3643NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3644{
3645 for (auto thread_sp : m_threads)
3646 {
3647 assert (thread_sp && "thread list should not contain NULL threads");
3648 if (thread_sp->GetID () == thread_id)
3649 {
3650 // We have this thread.
3651 return true;
3652 }
3653 }
3654
3655 // We don't have this thread.
3656 return false;
3657}
3658
3659NativeThreadProtocolSP
3660NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3661{
3662 // CONSIDER organize threads by map - we can do better than linear.
3663 for (auto thread_sp : m_threads)
3664 {
3665 if (thread_sp->GetID () == thread_id)
3666 return thread_sp;
3667 }
3668
3669 // We don't have this thread.
3670 return NativeThreadProtocolSP ();
3671}
3672
3673bool
3674NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3675{
3676 Mutex::Locker locker (m_threads_mutex);
3677 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3678 {
3679 if (*it && ((*it)->GetID () == thread_id))
3680 {
3681 m_threads.erase (it);
3682 return true;
3683 }
3684 }
3685
3686 // Didn't find it.
3687 return false;
3688}
3689
3690NativeThreadProtocolSP
3691NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3692{
3693 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3694
3695 Mutex::Locker locker (m_threads_mutex);
3696
3697 if (log)
3698 {
3699 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3700 __FUNCTION__,
3701 GetID (),
3702 thread_id);
3703 }
3704
3705 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3706
3707 // If this is the first thread, save it as the current thread
3708 if (m_threads.empty ())
3709 SetCurrentThreadID (thread_id);
3710
3711 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3712 m_threads.push_back (thread_sp);
3713
3714 return thread_sp;
3715}
3716
3717NativeThreadProtocolSP
3718NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3719{
3720 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3721
3722 Mutex::Locker locker (m_threads_mutex);
3723 if (log)
3724 {
3725 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3726 __FUNCTION__,
3727 GetID (),
3728 thread_id);
3729 }
3730
3731 // Retrieve the thread if it is already getting tracked.
3732 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3733 if (thread_sp)
3734 {
3735 if (log)
3736 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3737 __FUNCTION__,
3738 GetID (),
3739 thread_id);
3740 created = false;
3741 return thread_sp;
3742
3743 }
3744
3745 // Create the thread metadata since it isn't being tracked.
3746 if (log)
3747 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3748 __FUNCTION__,
3749 GetID (),
3750 thread_id);
3751
3752 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3753 m_threads.push_back (thread_sp);
3754 created = true;
3755
3756 return thread_sp;
3757}
3758
3759Error
3760NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3761{
Todd Fiala75f47c32014-10-11 21:42:09 +00003762 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003763
3764 Error error;
3765
3766 // Get a linux thread pointer.
3767 if (!thread_sp)
3768 {
3769 error.SetErrorString ("null thread_sp");
3770 if (log)
3771 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3772 return error;
3773 }
3774 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get());
3775
3776 // Find out the size of a breakpoint (might depend on where we are in the code).
3777 NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext ();
3778 if (!context_sp)
3779 {
3780 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3781 if (log)
3782 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3783 return error;
3784 }
3785
3786 uint32_t breakpoint_size = 0;
3787 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3788 if (error.Fail ())
3789 {
3790 if (log)
3791 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3792 return error;
3793 }
3794 else
3795 {
3796 if (log)
3797 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3798 }
3799
3800 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3801 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3802 lldb::addr_t breakpoint_addr = initial_pc_addr;
3803 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3804 {
3805 // Do not allow breakpoint probe to wrap around.
3806 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3807 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3808 }
3809
3810 // Check if we stopped because of a breakpoint.
3811 NativeBreakpointSP breakpoint_sp;
3812 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3813 if (!error.Success () || !breakpoint_sp)
3814 {
3815 // We didn't find one at a software probe location. Nothing to do.
3816 if (log)
3817 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3818 return Error ();
3819 }
3820
3821 // If the breakpoint is not a software breakpoint, nothing to do.
3822 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3823 {
3824 if (log)
3825 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3826 return Error ();
3827 }
3828
3829 //
3830 // We have a software breakpoint and need to adjust the PC.
3831 //
3832
3833 // Sanity check.
3834 if (breakpoint_size == 0)
3835 {
3836 // Nothing to do! How did we get here?
3837 if (log)
3838 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);
3839 return Error ();
3840 }
3841
3842 // Change the program counter.
3843 if (log)
3844 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);
3845
3846 error = context_sp->SetPC (breakpoint_addr);
3847 if (error.Fail ())
3848 {
3849 if (log)
3850 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ());
3851 return error;
3852 }
3853
3854 return error;
3855}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003856
3857void
3858NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3859{
3860 const bool is_stopped = true;
3861 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3862}
3863
3864void
3865NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3866{
3867 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3868}
3869
3870void
3871NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3872{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003873 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003874}
3875
3876void
3877NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3878 const std::function<void (lldb::tid_t tid)> &call_after_function)
3879{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003880 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3881 if (log)
3882 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3883
Chaoren Linfa03ad22015-02-03 01:50:42 +00003884 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003885 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003886 [=](lldb::tid_t request_stop_tid)
3887 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003888 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003889 },
3890 call_after_function,
3891 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003892}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003893
Chaoren Lin03f12d62015-02-03 01:50:49 +00003894void
3895NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3896 lldb::tid_t skip_stop_request_tid,
3897 const std::function<void (lldb::tid_t tid)> &call_after_function)
3898{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003899 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3900 if (log)
3901 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3902
Chaoren Lin03f12d62015-02-03 01:50:49 +00003903 const lldb::pid_t pid = GetID ();
3904 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3905 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3906 [=](lldb::tid_t request_stop_tid)
3907 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003908 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003909 },
3910 call_after_function,
3911 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003912}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003913
3914lldb_private::Error
3915NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3916{
3917 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3918 if (log)
3919 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3920
3921 Error err;
3922 errno = 0;
3923 if (::tgkill (pid, tid, SIGSTOP) != 0)
3924 {
3925 err.SetErrorToErrno ();
3926 if (log)
3927 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3928 }
3929
3930 return err;
3931}