blob: 13b9c27be0bfaa78ef82aa5616e708aa640e7148 [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>
20#include <linux/unistd.h>
Shawn Best8da0bf32014-11-08 01:41:49 +000021#if defined(__ANDROID_NDK__) && defined (__arm__)
22#include <linux/personality.h>
23#include <linux/user.h>
24#else
Todd Fiala0bce1b62014-08-17 00:10:50 +000025#include <sys/personality.h>
Shawn Best8da0bf32014-11-08 01:41:49 +000026#include <sys/user.h>
27#endif
Todd Fialacacde7d2014-09-27 16:54:22 +000028#ifndef __ANDROID__
Todd Fiala0fceef82014-09-15 17:09:23 +000029#include <sys/procfs.h>
Todd Fialacacde7d2014-09-27 16:54:22 +000030#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include <sys/ptrace.h>
Todd Fiala6ac1be42014-08-21 16:34:03 +000032#include <sys/uio.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000033#include <sys/socket.h>
34#include <sys/syscall.h>
35#include <sys/types.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000036#include <sys/wait.h>
37
Todd Fiala6ac1be42014-08-21 16:34:03 +000038#if defined (__arm64__) || defined (__aarch64__)
39// NT_PRSTATUS and NT_FPREGSET definition
40#include <elf.h>
41#endif
42
Todd Fialaaf245d12014-06-30 21:05:18 +000043// C++ Includes
44#include <fstream>
45#include <string>
46
47// Other libraries and framework includes
48#include "lldb/Core/Debugger.h"
49#include "lldb/Core/Error.h"
50#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000051#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000052#include "lldb/Core/RegisterValue.h"
53#include "lldb/Core/Scalar.h"
54#include "lldb/Core/State.h"
55#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000056#include "lldb/Host/HostInfo.h"
Zachary Turner39de3112014-09-09 20:54:56 +000057#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000058#include "lldb/Symbol/ObjectFile.h"
59#include "lldb/Target/NativeRegisterContext.h"
60#include "lldb/Target/ProcessLaunchInfo.h"
61#include "lldb/Utility/PseudoTerminal.h"
62
63#include "Host/common/NativeBreakpoint.h"
64#include "Utility/StringExtractor.h"
65
66#include "Plugins/Process/Utility/LinuxSignals.h"
67#include "NativeThreadLinux.h"
68#include "ProcFileReader.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000069#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000070#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
71
72#ifdef __ANDROID__
73#define __ptrace_request int
74#define PT_DETACH PTRACE_DETACH
75#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000076
77#define DEBUG_PTRACE_MAXBYTES 20
78
79// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000080#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000081#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000082 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000083#endif
Todd Fialadda61942014-07-02 21:34:04 +000084#endif
85#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000086#ifndef PTRACE_SETREGS
87 #define PTRACE_SETREGS 13
88#endif
Todd Fialadda61942014-07-02 21:34:04 +000089#endif
90#ifndef PT_GETFPREGS
91#ifndef PTRACE_GETFPREGS
92 #define PTRACE_GETFPREGS 14
93#endif
94#endif
95#ifndef PT_SETFPREGS
96#ifndef PTRACE_SETFPREGS
97 #define PTRACE_SETFPREGS 15
98#endif
99#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000100#ifndef PTRACE_GETREGSET
101 #define PTRACE_GETREGSET 0x4204
102#endif
103#ifndef PTRACE_SETREGSET
104 #define PTRACE_SETREGSET 0x4205
105#endif
106#ifndef PTRACE_GET_THREAD_AREA
107 #define PTRACE_GET_THREAD_AREA 25
108#endif
109#ifndef PTRACE_ARCH_PRCTL
110 #define PTRACE_ARCH_PRCTL 30
111#endif
112#ifndef ARCH_GET_FS
113 #define ARCH_SET_GS 0x1001
114 #define ARCH_SET_FS 0x1002
115 #define ARCH_GET_FS 0x1003
116 #define ARCH_GET_GS 0x1004
117#endif
118
Todd Fiala0bce1b62014-08-17 00:10:50 +0000119#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121// Support hardware breakpoints in case it has not been defined
122#ifndef TRAP_HWBKPT
123 #define TRAP_HWBKPT 4
124#endif
125
126// Try to define a macro to encapsulate the tgkill syscall
127// fall back on kill() if tgkill isn't available
128#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
129
130// We disable the tracing of ptrace calls for integration builds to
131// avoid the additional indirection and checks.
132#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000133#define PTRACE(req, pid, addr, data, data_size, error) \
134 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000135#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000136#define PTRACE(req, pid, addr, data, data_size, error) \
137 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000138#endif
139
140// Private bits we only need internally.
141namespace
142{
143 using namespace lldb;
144 using namespace lldb_private;
145
146 const UnixSignals&
147 GetUnixSignals ()
148 {
149 static process_linux::LinuxSignals signals;
150 return signals;
151 }
152
Chaoren Linfa03ad22015-02-03 01:50:42 +0000153 ThreadStateCoordinator::LogFunction
154 GetThreadLoggerFunction ()
155 {
156 return [](const char *format, va_list args)
157 {
158 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
159 if (log)
160 log->VAPrintf (format, args);
161 };
162 }
163
164 void
165 CoordinatorErrorHandler (const std::string &error_message)
166 {
167 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
168 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000169 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000170 assert (false && "ThreadStateCoordinator error reported");
171 }
172
Todd Fialaaf245d12014-06-30 21:05:18 +0000173 Error
174 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
175 {
176 // Grab process info for the running process.
177 ProcessInstanceInfo process_info;
178 if (!platform.GetProcessInfo (pid, process_info))
179 return lldb_private::Error("failed to get process info");
180
181 // Resolve the executable module.
182 ModuleSP exe_module_sp;
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000183 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), platform.GetSystemArchitecture ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000184 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
185 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000186 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000187 exe_module_sp,
188 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
189
190 if (!error.Success ())
191 return error;
192
193 // Check if we've got our architecture from the exe_module.
194 arch = exe_module_sp->GetArchitecture ();
195 if (arch.IsValid ())
196 return Error();
197 else
198 return Error("failed to retrieve a valid architecture from the exe module");
199 }
200
201 void
202 DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
203 {
204 uint8_t *ptr = (uint8_t *)bytes;
205 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
206 for(uint32_t i=0; i<loop_count; i++)
207 {
208 s.Printf ("[%x]", *ptr);
209 ptr++;
210 }
211 }
212
213 void
214 PtraceDisplayBytes(int &req, void *data, size_t data_size)
215 {
216 StreamString buf;
217 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
218 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
219
220 if (verbose_log)
221 {
222 switch(req)
223 {
224 case PTRACE_POKETEXT:
225 {
226 DisplayBytes(buf, &data, 8);
227 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
228 break;
229 }
230 case PTRACE_POKEDATA:
231 {
232 DisplayBytes(buf, &data, 8);
233 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
234 break;
235 }
236 case PTRACE_POKEUSER:
237 {
238 DisplayBytes(buf, &data, 8);
239 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
240 break;
241 }
242 case PTRACE_SETREGS:
243 {
244 DisplayBytes(buf, data, data_size);
245 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
246 break;
247 }
248 case PTRACE_SETFPREGS:
249 {
250 DisplayBytes(buf, data, data_size);
251 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
252 break;
253 }
254 case PTRACE_SETSIGINFO:
255 {
256 DisplayBytes(buf, data, sizeof(siginfo_t));
257 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
258 break;
259 }
260 case PTRACE_SETREGSET:
261 {
262 // Extract iov_base from data, which is a pointer to the struct IOVEC
263 DisplayBytes(buf, *(void **)data, data_size);
264 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
265 break;
266 }
267 default:
268 {
269 }
270 }
271 }
272 }
273
274 // Wrapper for ptrace to catch errors and log calls.
275 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
276 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000277 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
278 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000279 {
280 long int result;
281
282 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
283
284 PtraceDisplayBytes(req, data, data_size);
285
Chaoren Lin97ccc292015-02-03 01:51:12 +0000286 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000287 errno = 0;
288 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000289 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000291 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000292
Chaoren Lin97ccc292015-02-03 01:51:12 +0000293 if (result == -1)
294 error.SetErrorToErrno();
295
Todd Fialaaf245d12014-06-30 21:05:18 +0000296 if (log)
297 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
298 reqName, pid, addr, data, data_size, result, file, line);
299
300 PtraceDisplayBytes(req, data, data_size);
301
Chaoren Lin97ccc292015-02-03 01:51:12 +0000302 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000303 {
304 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000305 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 {
307 case ESRCH: str = "ESRCH"; break;
308 case EINVAL: str = "EINVAL"; break;
309 case EBUSY: str = "EBUSY"; break;
310 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000311 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000312 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000313 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000314 }
315
316 return result;
317 }
318
319#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
320 // Wrapper for ptrace when logging is not required.
321 // Sets errno to 0 prior to calling ptrace.
322 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000323 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000324 {
325 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000326
327 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000328 errno = 0;
329 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000330 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000332 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000333
334 if (result == -1)
335 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000336 return result;
337 }
338#endif
339
340 //------------------------------------------------------------------------------
341 // Static implementations of NativeProcessLinux::ReadMemory and
342 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
343 // functions without needed to go thru the thread funnel.
344
Chaoren Lin97ccc292015-02-03 01:51:12 +0000345 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000346 DoReadMemory (
347 lldb::pid_t pid,
348 lldb::addr_t vm_addr,
349 void *buf,
350 lldb::addr_t size,
351 Error &error)
352 {
353 // ptrace word size is determined by the host, not the child
354 static const unsigned word_size = sizeof(void*);
355 unsigned char *dst = static_cast<unsigned char*>(buf);
356 lldb::addr_t bytes_read;
357 lldb::addr_t remainder;
358 long data;
359
360 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
361 if (log)
362 ProcessPOSIXLog::IncNestLevel();
363 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
364 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
365 pid, word_size, (void*)vm_addr, buf, size);
366
367 assert(sizeof(data) >= word_size);
368 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
369 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000370 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
371 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000372 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000373 if (log)
374 ProcessPOSIXLog::DecNestLevel();
375 return bytes_read;
376 }
377
378 remainder = size - bytes_read;
379 remainder = remainder > word_size ? word_size : remainder;
380
381 // Copy the data into our buffer
382 for (unsigned i = 0; i < remainder; ++i)
383 dst[i] = ((data >> i*8) & 0xFF);
384
385 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
386 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
387 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
388 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
389 {
390 uintptr_t print_dst = 0;
391 // Format bytes from data by moving into print_dst for log output
392 for (unsigned i = 0; i < remainder; ++i)
393 print_dst |= (((data >> i*8) & 0xFF) << i*8);
394 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
395 (void*)vm_addr, print_dst, (unsigned long)data);
396 }
397
398 vm_addr += word_size;
399 dst += word_size;
400 }
401
402 if (log)
403 ProcessPOSIXLog::DecNestLevel();
404 return bytes_read;
405 }
406
Chaoren Lin97ccc292015-02-03 01:51:12 +0000407 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000408 DoWriteMemory(
409 lldb::pid_t pid,
410 lldb::addr_t vm_addr,
411 const void *buf,
412 lldb::addr_t size,
413 Error &error)
414 {
415 // ptrace word size is determined by the host, not the child
416 static const unsigned word_size = sizeof(void*);
417 const unsigned char *src = static_cast<const unsigned char*>(buf);
418 lldb::addr_t bytes_written = 0;
419 lldb::addr_t remainder;
420
421 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
422 if (log)
423 ProcessPOSIXLog::IncNestLevel();
424 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
425 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
426 pid, word_size, (void*)vm_addr, buf, size);
427
428 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
429 {
430 remainder = size - bytes_written;
431 remainder = remainder > word_size ? word_size : remainder;
432
433 if (remainder == word_size)
434 {
435 unsigned long data = 0;
436 assert(sizeof(data) >= word_size);
437 for (unsigned i = 0; i < word_size; ++i)
438 data |= (unsigned long)src[i] << i*8;
439
440 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
441 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
442 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
443 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
444 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
445 (void*)vm_addr, *(unsigned long*)src, data);
446
Chaoren Lin97ccc292015-02-03 01:51:12 +0000447 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000448 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000449 if (log)
450 ProcessPOSIXLog::DecNestLevel();
451 return bytes_written;
452 }
453 }
454 else
455 {
456 unsigned char buff[8];
457 if (DoReadMemory(pid, vm_addr,
458 buff, word_size, error) != word_size)
459 {
460 if (log)
461 ProcessPOSIXLog::DecNestLevel();
462 return bytes_written;
463 }
464
465 memcpy(buff, src, remainder);
466
467 if (DoWriteMemory(pid, vm_addr,
468 buff, word_size, error) != word_size)
469 {
470 if (log)
471 ProcessPOSIXLog::DecNestLevel();
472 return bytes_written;
473 }
474
475 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
476 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
477 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
478 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
479 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
480 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
481 }
482
483 vm_addr += word_size;
484 src += word_size;
485 }
486 if (log)
487 ProcessPOSIXLog::DecNestLevel();
488 return bytes_written;
489 }
490
491 //------------------------------------------------------------------------------
492 /// @class Operation
493 /// @brief Represents a NativeProcessLinux operation.
494 ///
495 /// Under Linux, it is not possible to ptrace() from any other thread but the
496 /// one that spawned or attached to the process from the start. Therefore, when
497 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
498 /// process the operation must be "funneled" to a specific thread to perform the
499 /// task. The Operation class provides an abstract base for all services the
500 /// NativeProcessLinux must perform via the single virtual function Execute, thus
501 /// encapsulating the code that needs to run in the privileged context.
502 class Operation
503 {
504 public:
505 Operation () : m_error() { }
506
507 virtual
508 ~Operation() {}
509
510 virtual void
511 Execute (NativeProcessLinux *process) = 0;
512
513 const Error &
514 GetError () const { return m_error; }
515
516 protected:
517 Error m_error;
518 };
519
520 //------------------------------------------------------------------------------
521 /// @class ReadOperation
522 /// @brief Implements NativeProcessLinux::ReadMemory.
523 class ReadOperation : public Operation
524 {
525 public:
526 ReadOperation (
527 lldb::addr_t addr,
528 void *buff,
529 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000530 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000531 Operation (),
532 m_addr (addr),
533 m_buff (buff),
534 m_size (size),
535 m_result (result)
536 {
537 }
538
539 void Execute (NativeProcessLinux *process) override;
540
541 private:
542 lldb::addr_t m_addr;
543 void *m_buff;
544 lldb::addr_t m_size;
545 lldb::addr_t &m_result;
546 };
547
548 void
549 ReadOperation::Execute (NativeProcessLinux *process)
550 {
551 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
552 }
553
554 //------------------------------------------------------------------------------
555 /// @class WriteOperation
556 /// @brief Implements NativeProcessLinux::WriteMemory.
557 class WriteOperation : public Operation
558 {
559 public:
560 WriteOperation (
561 lldb::addr_t addr,
562 const void *buff,
563 lldb::addr_t size,
564 lldb::addr_t &result) :
565 Operation (),
566 m_addr (addr),
567 m_buff (buff),
568 m_size (size),
569 m_result (result)
570 {
571 }
572
573 void Execute (NativeProcessLinux *process) override;
574
575 private:
576 lldb::addr_t m_addr;
577 const void *m_buff;
578 lldb::addr_t m_size;
579 lldb::addr_t &m_result;
580 };
581
582 void
583 WriteOperation::Execute(NativeProcessLinux *process)
584 {
585 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
586 }
587
588 //------------------------------------------------------------------------------
589 /// @class ReadRegOperation
590 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
591 class ReadRegOperation : public Operation
592 {
593 public:
594 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000595 RegisterValue &value)
596 : m_tid(tid),
597 m_offset(static_cast<uintptr_t> (offset)),
598 m_reg_name(reg_name),
599 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000600 { }
601
602 void Execute(NativeProcessLinux *monitor);
603
604 private:
605 lldb::tid_t m_tid;
606 uintptr_t m_offset;
607 const char *m_reg_name;
608 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000609 };
610
611 void
612 ReadRegOperation::Execute(NativeProcessLinux *monitor)
613 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000614#if defined (__arm64__) || defined (__aarch64__)
615 if (m_offset > sizeof(struct user_pt_regs))
616 {
617 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
618 if (offset > sizeof(struct user_fpsimd_state))
619 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000620 m_error.SetErrorString("invalid offset value");
621 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000622 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000623 elf_fpregset_t regs;
624 int regset = NT_FPREGSET;
625 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000626
Chaoren Lin97ccc292015-02-03 01:51:12 +0000627 ioVec.iov_base = &regs;
628 ioVec.iov_len = sizeof regs;
629 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
630 if (m_error.Success())
631 {
632 lldb_private::ArchSpec arch;
633 if (monitor->GetArchitecture(arch))
634 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000635 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000636 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000637 }
638 }
639 else
640 {
641 elf_gregset_t regs;
642 int regset = NT_PRSTATUS;
643 struct iovec ioVec;
644
645 ioVec.iov_base = &regs;
646 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000647 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
648 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000649 {
650 lldb_private::ArchSpec arch;
651 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000652 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000653 else
654 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 }
656 }
657#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000658 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
659
Chaoren Lin97ccc292015-02-03 01:51:12 +0000660 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error);
661 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000662 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000663
Todd Fialaaf245d12014-06-30 21:05:18 +0000664 if (log)
665 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
666 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000667#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000668 }
669
670 //------------------------------------------------------------------------------
671 /// @class WriteRegOperation
672 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
673 class WriteRegOperation : public Operation
674 {
675 public:
676 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000677 const RegisterValue &value)
678 : m_tid(tid),
679 m_offset(offset),
680 m_reg_name(reg_name),
681 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 { }
683
684 void Execute(NativeProcessLinux *monitor);
685
686 private:
687 lldb::tid_t m_tid;
688 uintptr_t m_offset;
689 const char *m_reg_name;
690 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000691 };
692
693 void
694 WriteRegOperation::Execute(NativeProcessLinux *monitor)
695 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000696#if defined (__arm64__) || defined (__aarch64__)
697 if (m_offset > sizeof(struct user_pt_regs))
698 {
699 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
700 if (offset > sizeof(struct user_fpsimd_state))
701 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000702 m_error.SetErrorString("invalid offset value");
703 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000704 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000705 elf_fpregset_t regs;
706 int regset = NT_FPREGSET;
707 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000708
Chaoren Lin97ccc292015-02-03 01:51:12 +0000709 ioVec.iov_base = &regs;
710 ioVec.iov_len = sizeof regs;
711 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
712 if (m_error.Sucess())
713 {
714 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
715 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000716 }
717 }
718 else
719 {
720 elf_gregset_t regs;
721 int regset = NT_PRSTATUS;
722 struct iovec ioVec;
723
724 ioVec.iov_base = &regs;
725 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000726 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
727 if (m_error.Sucess())
Todd Fiala0fceef82014-09-15 17:09:23 +0000728 {
729 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000730 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000731 }
732 }
733#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000734 void* buf;
735 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
736
737 buf = (void*) m_value.GetAsUInt64();
738
739 if (log)
740 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000741 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000742#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000743 }
744
745 //------------------------------------------------------------------------------
746 /// @class ReadGPROperation
747 /// @brief Implements NativeProcessLinux::ReadGPR.
748 class ReadGPROperation : public Operation
749 {
750 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000751 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
752 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000753 { }
754
755 void Execute(NativeProcessLinux *monitor);
756
757 private:
758 lldb::tid_t m_tid;
759 void *m_buf;
760 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000761 };
762
763 void
764 ReadGPROperation::Execute(NativeProcessLinux *monitor)
765 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000766#if defined (__arm64__) || defined (__aarch64__)
767 int regset = NT_PRSTATUS;
768 struct iovec ioVec;
769
770 ioVec.iov_base = m_buf;
771 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000772 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000773#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000774 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000775#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000776 }
777
778 //------------------------------------------------------------------------------
779 /// @class ReadFPROperation
780 /// @brief Implements NativeProcessLinux::ReadFPR.
781 class ReadFPROperation : public Operation
782 {
783 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000784 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
785 : m_tid(tid),
786 m_buf(buf),
787 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000788 { }
789
790 void Execute(NativeProcessLinux *monitor);
791
792 private:
793 lldb::tid_t m_tid;
794 void *m_buf;
795 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000796 };
797
798 void
799 ReadFPROperation::Execute(NativeProcessLinux *monitor)
800 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000801#if defined (__arm64__) || defined (__aarch64__)
802 int regset = NT_FPREGSET;
803 struct iovec ioVec;
804
805 ioVec.iov_base = m_buf;
806 ioVec.iov_len = m_buf_size;
807 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
808 m_result = false;
809 else
810 m_result = true;
811#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000812 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000813#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000814 }
815
816 //------------------------------------------------------------------------------
817 /// @class ReadRegisterSetOperation
818 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
819 class ReadRegisterSetOperation : public Operation
820 {
821 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000822 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
823 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000824 { }
825
826 void Execute(NativeProcessLinux *monitor);
827
828 private:
829 lldb::tid_t m_tid;
830 void *m_buf;
831 size_t m_buf_size;
832 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 };
834
835 void
836 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
837 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000838 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000839 }
840
841 //------------------------------------------------------------------------------
842 /// @class WriteGPROperation
843 /// @brief Implements NativeProcessLinux::WriteGPR.
844 class WriteGPROperation : public Operation
845 {
846 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000847 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
848 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000849 { }
850
851 void Execute(NativeProcessLinux *monitor);
852
853 private:
854 lldb::tid_t m_tid;
855 void *m_buf;
856 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000857 };
858
859 void
860 WriteGPROperation::Execute(NativeProcessLinux *monitor)
861 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000862#if defined (__arm64__) || defined (__aarch64__)
863 int regset = NT_PRSTATUS;
864 struct iovec ioVec;
865
866 ioVec.iov_base = m_buf;
867 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000868 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000869#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000870 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000871#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000872 }
873
874 //------------------------------------------------------------------------------
875 /// @class WriteFPROperation
876 /// @brief Implements NativeProcessLinux::WriteFPR.
877 class WriteFPROperation : public Operation
878 {
879 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000880 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
881 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000882 { }
883
884 void Execute(NativeProcessLinux *monitor);
885
886 private:
887 lldb::tid_t m_tid;
888 void *m_buf;
889 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000890 };
891
892 void
893 WriteFPROperation::Execute(NativeProcessLinux *monitor)
894 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000895#if defined (__arm64__) || defined (__aarch64__)
896 int regset = NT_FPREGSET;
897 struct iovec ioVec;
898
899 ioVec.iov_base = m_buf;
900 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000901 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000902#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000903 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000904#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000905 }
906
907 //------------------------------------------------------------------------------
908 /// @class WriteRegisterSetOperation
909 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
910 class WriteRegisterSetOperation : public Operation
911 {
912 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000913 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
914 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000915 { }
916
917 void Execute(NativeProcessLinux *monitor);
918
919 private:
920 lldb::tid_t m_tid;
921 void *m_buf;
922 size_t m_buf_size;
923 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 };
925
926 void
927 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
928 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000929 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000930 }
931
932 //------------------------------------------------------------------------------
933 /// @class ResumeOperation
934 /// @brief Implements NativeProcessLinux::Resume.
935 class ResumeOperation : public Operation
936 {
937 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000938 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
939 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000940
941 void Execute(NativeProcessLinux *monitor);
942
943 private:
944 lldb::tid_t m_tid;
945 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000946 };
947
948 void
949 ResumeOperation::Execute(NativeProcessLinux *monitor)
950 {
951 intptr_t data = 0;
952
953 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
954 data = m_signo;
955
Chaoren Lin97ccc292015-02-03 01:51:12 +0000956 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
957 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000958 {
959 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
960
961 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000962 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000964 }
965
966 //------------------------------------------------------------------------------
967 /// @class SingleStepOperation
968 /// @brief Implements NativeProcessLinux::SingleStep.
969 class SingleStepOperation : public Operation
970 {
971 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000972 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
973 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000974
975 void Execute(NativeProcessLinux *monitor);
976
977 private:
978 lldb::tid_t m_tid;
979 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000980 };
981
982 void
983 SingleStepOperation::Execute(NativeProcessLinux *monitor)
984 {
985 intptr_t data = 0;
986
987 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
988 data = m_signo;
989
Chaoren Lin97ccc292015-02-03 01:51:12 +0000990 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000991 }
992
993 //------------------------------------------------------------------------------
994 /// @class SiginfoOperation
995 /// @brief Implements NativeProcessLinux::GetSignalInfo.
996 class SiginfoOperation : public Operation
997 {
998 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000999 SiginfoOperation(lldb::tid_t tid, void *info)
1000 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001001
1002 void Execute(NativeProcessLinux *monitor);
1003
1004 private:
1005 lldb::tid_t m_tid;
1006 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001007 };
1008
1009 void
1010 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1011 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001012 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001013 }
1014
1015 //------------------------------------------------------------------------------
1016 /// @class EventMessageOperation
1017 /// @brief Implements NativeProcessLinux::GetEventMessage.
1018 class EventMessageOperation : public Operation
1019 {
1020 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001021 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1022 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001023
1024 void Execute(NativeProcessLinux *monitor);
1025
1026 private:
1027 lldb::tid_t m_tid;
1028 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001029 };
1030
1031 void
1032 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1033 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001034 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001035 }
1036
1037 class DetachOperation : public Operation
1038 {
1039 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001040 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001041
1042 void Execute(NativeProcessLinux *monitor);
1043
1044 private:
1045 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001046 };
1047
1048 void
1049 DetachOperation::Execute(NativeProcessLinux *monitor)
1050 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001051 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001052 }
1053
1054}
1055
1056using namespace lldb_private;
1057
1058// Simple helper function to ensure flags are enabled on the given file
1059// descriptor.
1060static bool
1061EnsureFDFlags(int fd, int flags, Error &error)
1062{
1063 int status;
1064
1065 if ((status = fcntl(fd, F_GETFL)) == -1)
1066 {
1067 error.SetErrorToErrno();
1068 return false;
1069 }
1070
1071 if (fcntl(fd, F_SETFL, status | flags) == -1)
1072 {
1073 error.SetErrorToErrno();
1074 return false;
1075 }
1076
1077 return true;
1078}
1079
1080NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1081 : m_monitor(monitor)
1082{
1083 sem_init(&m_semaphore, 0, 0);
1084}
1085
1086NativeProcessLinux::OperationArgs::~OperationArgs()
1087{
1088 sem_destroy(&m_semaphore);
1089}
1090
1091NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
1092 lldb_private::Module *module,
1093 char const **argv,
1094 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001095 const std::string &stdin_path,
1096 const std::string &stdout_path,
1097 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001098 const char *working_dir,
1099 const lldb_private::ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001100 : OperationArgs(monitor),
1101 m_module(module),
1102 m_argv(argv),
1103 m_envp(envp),
1104 m_stdin_path(stdin_path),
1105 m_stdout_path(stdout_path),
1106 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001107 m_working_dir(working_dir),
1108 m_launch_info(launch_info)
1109{
1110}
Todd Fialaaf245d12014-06-30 21:05:18 +00001111
1112NativeProcessLinux::LaunchArgs::~LaunchArgs()
1113{ }
1114
1115NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1116 lldb::pid_t pid)
1117 : OperationArgs(monitor), m_pid(pid) { }
1118
1119NativeProcessLinux::AttachArgs::~AttachArgs()
1120{ }
1121
1122// -----------------------------------------------------------------------------
1123// Public Static Methods
1124// -----------------------------------------------------------------------------
1125
1126lldb_private::Error
1127NativeProcessLinux::LaunchProcess (
1128 lldb_private::Module *exe_module,
1129 lldb_private::ProcessLaunchInfo &launch_info,
1130 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1131 NativeProcessProtocolSP &native_process_sp)
1132{
1133 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1134
1135 Error error;
1136
1137 // Verify the working directory is valid if one was specified.
1138 const char* working_dir = launch_info.GetWorkingDirectory ();
1139 if (working_dir)
1140 {
1141 FileSpec working_dir_fs (working_dir, true);
1142 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1143 {
1144 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1145 return error;
1146 }
1147 }
1148
Zachary Turner696b5282014-08-14 16:01:25 +00001149 const lldb_private::FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001150
1151 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001152 std::string stdin_path;
1153 std::string stdout_path;
1154 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001155
1156 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001157 if (file_action)
1158 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001159
1160 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001161 if (file_action)
1162 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001163
1164 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001165 if (file_action)
1166 stderr_path = file_action->GetPath ();
1167
1168 if (log)
1169 {
1170 if (!stdin_path.empty ())
1171 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1172 else
1173 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1174
1175 if (!stdout_path.empty ())
1176 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1177 else
1178 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1179
1180 if (!stderr_path.empty ())
1181 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1182 else
1183 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1184 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001185
1186 // Create the NativeProcessLinux in launch mode.
1187 native_process_sp.reset (new NativeProcessLinux ());
1188
1189 if (log)
1190 {
1191 int i = 0;
1192 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1193 {
1194 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1195 ++i;
1196 }
1197 }
1198
1199 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1200 {
1201 native_process_sp.reset ();
1202 error.SetErrorStringWithFormat ("failed to register the native delegate");
1203 return error;
1204 }
1205
1206 reinterpret_cast<NativeProcessLinux*> (native_process_sp.get ())->LaunchInferior (
1207 exe_module,
1208 launch_info.GetArguments ().GetConstArgumentVector (),
1209 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1210 stdin_path,
1211 stdout_path,
1212 stderr_path,
1213 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001214 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001215 error);
1216
1217 if (error.Fail ())
1218 {
1219 native_process_sp.reset ();
1220 if (log)
1221 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1222 return error;
1223 }
1224
1225 launch_info.SetProcessID (native_process_sp->GetID ());
1226
1227 return error;
1228}
1229
1230lldb_private::Error
1231NativeProcessLinux::AttachToProcess (
1232 lldb::pid_t pid,
1233 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1234 NativeProcessProtocolSP &native_process_sp)
1235{
1236 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1237 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1238 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1239
1240 // Grab the current platform architecture. This should be Linux,
1241 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001242 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001243 if (!platform_sp)
1244 return Error("failed to get a valid default platform");
1245
1246 // Retrieve the architecture for the running process.
1247 ArchSpec process_arch;
1248 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1249 if (!error.Success ())
1250 return error;
1251
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001252 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001253
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001254 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001255 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001256 error.SetErrorStringWithFormat ("failed to register the native delegate");
1257 return error;
1258 }
1259
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001260 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001261 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001262 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001263
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001264 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001265 return error;
1266}
1267
1268// -----------------------------------------------------------------------------
1269// Public Instance Methods
1270// -----------------------------------------------------------------------------
1271
1272NativeProcessLinux::NativeProcessLinux () :
1273 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1274 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001275 m_operation_thread (),
1276 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001277 m_operation (nullptr),
1278 m_operation_mutex (),
1279 m_operation_pending (),
1280 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001281 m_supports_mem_region (eLazyBoolCalculate),
1282 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001283 m_mem_region_cache_mutex (),
1284 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1285 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001286{
1287}
1288
1289//------------------------------------------------------------------------------
1290/// The basic design of the NativeProcessLinux is built around two threads.
1291///
1292/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1293/// for changes in the debugee state. When a change is detected a
1294/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1295/// "drives" state changes in the debugger.
1296///
1297/// The second thread (@see OperationThread) is responsible for two things 1)
1298/// launching or attaching to the inferior process, and then 2) servicing
1299/// operations such as register reads/writes, stepping, etc. See the comments
1300/// on the Operation class for more info as to why this is needed.
1301void
1302NativeProcessLinux::LaunchInferior (
1303 Module *module,
1304 const char *argv[],
1305 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001306 const std::string &stdin_path,
1307 const std::string &stdout_path,
1308 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001309 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001310 const lldb_private::ProcessLaunchInfo &launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 lldb_private::Error &error)
1312{
1313 if (module)
1314 m_arch = module->GetArchitecture ();
1315
Chaoren Linfa03ad22015-02-03 01:50:42 +00001316 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001317
1318 std::unique_ptr<LaunchArgs> args(
1319 new LaunchArgs(
1320 this, module, argv, envp,
1321 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001322 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001323
Chaoren Linfa03ad22015-02-03 01:50:42 +00001324 sem_init (&m_operation_pending, 0, 0);
1325 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001326
Chaoren Linfa03ad22015-02-03 01:50:42 +00001327 StartLaunchOpThread (args.get(), error);
1328 if (!error.Success ())
1329 return;
1330
1331 error = StartCoordinatorThread ();
1332 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001333 return;
1334
1335WAIT_AGAIN:
1336 // Wait for the operation thread to initialize.
1337 if (sem_wait(&args->m_semaphore))
1338 {
1339 if (errno == EINTR)
1340 goto WAIT_AGAIN;
1341 else
1342 {
1343 error.SetErrorToErrno();
1344 return;
1345 }
1346 }
1347
1348 // Check that the launch was a success.
1349 if (!args->m_error.Success())
1350 {
1351 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001352 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001353 error = args->m_error;
1354 return;
1355 }
1356
1357 // Finally, start monitoring the child process for change in state.
1358 m_monitor_thread = Host::StartMonitoringChildProcess(
1359 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001360 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001361 {
1362 error.SetErrorToGenericError();
1363 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1364 return;
1365 }
1366}
1367
1368void
1369NativeProcessLinux::AttachToInferior (lldb::pid_t pid, lldb_private::Error &error)
1370{
1371 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1372 if (log)
1373 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1374
1375 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001376 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001377 if (!platform_sp)
1378 {
1379 if (log)
1380 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1381 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001382 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001383 }
1384
1385 // Gather info about the process.
1386 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001387 if (!platform_sp->GetProcessInfo (pid, process_info))
1388 {
1389 if (log)
1390 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1391 error.SetErrorString ("failed to get process info");
1392 return;
1393 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001394
1395 // Resolve the executable module
1396 ModuleSP exe_module_sp;
1397 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001398 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), HostInfo::GetArchitecture());
1399 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001400 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001401 if (!error.Success())
1402 return;
1403
1404 // Set the architecture to the exe architecture.
1405 m_arch = exe_module_sp->GetArchitecture();
1406 if (log)
1407 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1408
1409 m_pid = pid;
1410 SetState(eStateAttaching);
1411
1412 sem_init (&m_operation_pending, 0, 0);
1413 sem_init (&m_operation_done, 0, 0);
1414
1415 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1416
1417 StartAttachOpThread(args.get (), error);
1418 if (!error.Success ())
1419 return;
1420
Chaoren Linfa03ad22015-02-03 01:50:42 +00001421 error = StartCoordinatorThread ();
1422 if (!error.Success ())
1423 return;
1424
Todd Fialaaf245d12014-06-30 21:05:18 +00001425WAIT_AGAIN:
1426 // Wait for the operation thread to initialize.
1427 if (sem_wait (&args->m_semaphore))
1428 {
1429 if (errno == EINTR)
1430 goto WAIT_AGAIN;
1431 else
1432 {
1433 error.SetErrorToErrno ();
1434 return;
1435 }
1436 }
1437
1438 // Check that the attach was a success.
1439 if (!args->m_error.Success ())
1440 {
1441 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001442 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001443 error = args->m_error;
1444 return;
1445 }
1446
1447 // Finally, start monitoring the child process for change in state.
1448 m_monitor_thread = Host::StartMonitoringChildProcess (
1449 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001450 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001451 {
1452 error.SetErrorToGenericError ();
1453 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1454 return;
1455 }
1456}
1457
1458NativeProcessLinux::~NativeProcessLinux()
1459{
1460 StopMonitor();
1461}
1462
1463//------------------------------------------------------------------------------
1464// Thread setup and tear down.
1465
1466void
1467NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1468{
1469 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1470
Zachary Turneracee96a2014-09-23 18:32:09 +00001471 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001472 return;
1473
Zachary Turner39de3112014-09-09 20:54:56 +00001474 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001475}
1476
1477void *
1478NativeProcessLinux::LaunchOpThread(void *arg)
1479{
1480 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1481
1482 if (!Launch(args)) {
1483 sem_post(&args->m_semaphore);
1484 return NULL;
1485 }
1486
1487 ServeOperation(args);
1488 return NULL;
1489}
1490
1491bool
1492NativeProcessLinux::Launch(LaunchArgs *args)
1493{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001494 assert (args && "null args");
1495 if (!args)
1496 return false;
1497
Todd Fialaaf245d12014-06-30 21:05:18 +00001498 NativeProcessLinux *monitor = args->m_monitor;
1499 assert (monitor && "monitor is NULL");
1500 if (!monitor)
1501 return false;
1502
1503 const char **argv = args->m_argv;
1504 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001505 const char *working_dir = args->m_working_dir;
1506
1507 lldb_utility::PseudoTerminal terminal;
1508 const size_t err_len = 1024;
1509 char err_str[err_len];
1510 lldb::pid_t pid;
1511 NativeThreadProtocolSP thread_sp;
1512
1513 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001514
1515 // Propagate the environment if one is not supplied.
1516 if (envp == NULL || envp[0] == NULL)
1517 envp = const_cast<const char **>(environ);
1518
1519 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1520 {
1521 args->m_error.SetErrorToGenericError();
1522 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001523 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001524 }
1525
1526 // Recognized child exit status codes.
1527 enum {
1528 ePtraceFailed = 1,
1529 eDupStdinFailed,
1530 eDupStdoutFailed,
1531 eDupStderrFailed,
1532 eChdirFailed,
1533 eExecFailed,
1534 eSetGidFailed
1535 };
1536
1537 // Child process.
1538 if (pid == 0)
1539 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001540 // FIXME consider opening a pipe between parent/child and have this forked child
1541 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001542
Todd Fiala75f47c32014-10-11 21:42:09 +00001543 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001544 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1545 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001546 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001547
1548 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001549 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001550 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001551
1552 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001553 if (setpgid(0, 0) != 0)
1554 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001555 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001556 // Don't allow this to prevent an inferior exec.
1557 }
1558
1559 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001560 if (!args->m_stdin_path.empty ())
1561 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001562 exit(eDupStdinFailed);
1563
Todd Fiala75f47c32014-10-11 21:42:09 +00001564 if (!args->m_stdout_path.empty ())
1565 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT))
Todd Fialaaf245d12014-06-30 21:05:18 +00001566 exit(eDupStdoutFailed);
1567
Todd Fiala75f47c32014-10-11 21:42:09 +00001568 if (!args->m_stderr_path.empty ())
1569 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT))
Todd Fialaaf245d12014-06-30 21:05:18 +00001570 exit(eDupStderrFailed);
1571
1572 // Change working directory
1573 if (working_dir != NULL && working_dir[0])
1574 if (0 != ::chdir(working_dir))
1575 exit(eChdirFailed);
1576
Todd Fiala0bce1b62014-08-17 00:10:50 +00001577 // Disable ASLR if requested.
1578 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1579 {
1580 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1581 if (old_personality == -1)
1582 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001583 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001584 }
1585 else
1586 {
1587 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1588 if (new_personality == -1)
1589 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001590 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001591 }
1592 else
1593 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001594 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001595 }
1596 }
1597 }
1598
Todd Fiala75f47c32014-10-11 21:42:09 +00001599 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001600 execve(argv[0],
1601 const_cast<char *const *>(argv),
1602 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001603
1604 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001605 exit(eExecFailed);
1606 }
1607
Todd Fiala75f47c32014-10-11 21:42:09 +00001608 //
1609 // This is the parent code here.
1610 //
1611 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1612
Todd Fialaaf245d12014-06-30 21:05:18 +00001613 // Wait for the child process to trap on its call to execve.
1614 ::pid_t wpid;
1615 int status;
1616 if ((wpid = waitpid(pid, &status, 0)) < 0)
1617 {
1618 args->m_error.SetErrorToErrno();
1619
1620 if (log)
1621 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1622
1623 // Mark the inferior as invalid.
1624 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1625 monitor->SetState (StateType::eStateInvalid);
1626
Todd Fiala75f47c32014-10-11 21:42:09 +00001627 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001628 }
1629 else if (WIFEXITED(status))
1630 {
1631 // open, dup or execve likely failed for some reason.
1632 args->m_error.SetErrorToGenericError();
1633 switch (WEXITSTATUS(status))
1634 {
1635 case ePtraceFailed:
1636 args->m_error.SetErrorString("Child ptrace failed.");
1637 break;
1638 case eDupStdinFailed:
1639 args->m_error.SetErrorString("Child open stdin failed.");
1640 break;
1641 case eDupStdoutFailed:
1642 args->m_error.SetErrorString("Child open stdout failed.");
1643 break;
1644 case eDupStderrFailed:
1645 args->m_error.SetErrorString("Child open stderr failed.");
1646 break;
1647 case eChdirFailed:
1648 args->m_error.SetErrorString("Child failed to set working directory.");
1649 break;
1650 case eExecFailed:
1651 args->m_error.SetErrorString("Child exec failed.");
1652 break;
1653 case eSetGidFailed:
1654 args->m_error.SetErrorString("Child setgid failed.");
1655 break;
1656 default:
1657 args->m_error.SetErrorString("Child returned unknown exit status.");
1658 break;
1659 }
1660
1661 if (log)
1662 {
1663 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1664 __FUNCTION__,
1665 WEXITSTATUS(status));
1666 }
1667
1668 // Mark the inferior as invalid.
1669 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1670 monitor->SetState (StateType::eStateInvalid);
1671
Todd Fiala75f47c32014-10-11 21:42:09 +00001672 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001673 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001674 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001675 "Could not sync with inferior process.");
1676
1677 if (log)
1678 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1679
Chaoren Lin97ccc292015-02-03 01:51:12 +00001680 args->m_error = SetDefaultPtraceOpts(pid);
1681 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001682 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001683 if (log)
1684 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1685 __FUNCTION__,
1686 args->m_error.AsCString ());
1687
1688 // Mark the inferior as invalid.
1689 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1690 monitor->SetState (StateType::eStateInvalid);
1691
Todd Fiala75f47c32014-10-11 21:42:09 +00001692 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001693 }
1694
1695 // Release the master terminal descriptor and pass it off to the
1696 // NativeProcessLinux instance. Similarly stash the inferior pid.
1697 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1698 monitor->m_pid = pid;
1699
1700 // Set the terminal fd to be in non blocking mode (it simplifies the
1701 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1702 // descriptor to read from).
1703 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1704 {
1705 if (log)
1706 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1707 __FUNCTION__,
1708 args->m_error.AsCString ());
1709
1710 // Mark the inferior as invalid.
1711 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1712 monitor->SetState (StateType::eStateInvalid);
1713
Todd Fiala75f47c32014-10-11 21:42:09 +00001714 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001715 }
1716
1717 if (log)
1718 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1719
Chaoren Linfa03ad22015-02-03 01:50:42 +00001720 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001721 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001722 monitor->NotifyThreadCreateStopped (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001723 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001724
1725 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001726 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001727 monitor->SetState (StateType::eStateStopped);
1728
Todd Fialaaf245d12014-06-30 21:05:18 +00001729 if (log)
1730 {
1731 if (args->m_error.Success ())
1732 {
1733 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1734 }
1735 else
1736 {
1737 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1738 __FUNCTION__,
1739 args->m_error.AsCString ());
1740 }
1741 }
1742 return args->m_error.Success();
1743}
1744
1745void
1746NativeProcessLinux::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1747{
1748 static const char *g_thread_name = "lldb.process.linux.operation";
1749
Zachary Turneracee96a2014-09-23 18:32:09 +00001750 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001751 return;
1752
Zachary Turner39de3112014-09-09 20:54:56 +00001753 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001754}
1755
1756void *
1757NativeProcessLinux::AttachOpThread(void *arg)
1758{
1759 AttachArgs *args = static_cast<AttachArgs*>(arg);
1760
1761 if (!Attach(args)) {
1762 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001763 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001764 }
1765
1766 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001767 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001768}
1769
1770bool
1771NativeProcessLinux::Attach(AttachArgs *args)
1772{
1773 lldb::pid_t pid = args->m_pid;
1774
1775 NativeProcessLinux *monitor = args->m_monitor;
1776 lldb::ThreadSP inferior;
1777 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1778
1779 // Use a map to keep track of the threads which we have attached/need to attach.
1780 Host::TidMap tids_to_attach;
1781 if (pid <= 1)
1782 {
1783 args->m_error.SetErrorToGenericError();
1784 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1785 goto FINISH;
1786 }
1787
1788 while (Host::FindProcessThreads(pid, tids_to_attach))
1789 {
1790 for (Host::TidMap::iterator it = tids_to_attach.begin();
1791 it != tids_to_attach.end();)
1792 {
1793 if (it->second == false)
1794 {
1795 lldb::tid_t tid = it->first;
1796
1797 // Attach to the requested process.
1798 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001799 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1800 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001801 {
1802 // No such thread. The thread may have exited.
1803 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001804 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001805 {
1806 it = tids_to_attach.erase(it);
1807 continue;
1808 }
1809 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001810 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001811 }
1812
1813 int status;
1814 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1815 // At this point we should have a thread stopped if waitpid succeeds.
1816 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1817 {
1818 // No such thread. The thread may have exited.
1819 // More error handling may be needed.
1820 if (errno == ESRCH)
1821 {
1822 it = tids_to_attach.erase(it);
1823 continue;
1824 }
1825 else
1826 {
1827 args->m_error.SetErrorToErrno();
1828 goto FINISH;
1829 }
1830 }
1831
Chaoren Lin97ccc292015-02-03 01:51:12 +00001832 args->m_error = SetDefaultPtraceOpts(tid);
1833 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001834 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001835
1836
1837 if (log)
1838 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1839
1840 it->second = true;
1841
1842 // Create the thread, mark it as stopped.
1843 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1844 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001845
1846 // This will notify this is a new thread and tell the system it is stopped.
1847 monitor->NotifyThreadCreateStopped (tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001848 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
1849 monitor->SetCurrentThreadID (thread_sp->GetID ());
1850 }
1851
1852 // move the loop forward
1853 ++it;
1854 }
1855 }
1856
1857 if (tids_to_attach.size() > 0)
1858 {
1859 monitor->m_pid = pid;
1860 // Let our process instance know the thread has stopped.
1861 monitor->SetState (StateType::eStateStopped);
1862 }
1863 else
1864 {
1865 args->m_error.SetErrorToGenericError();
1866 args->m_error.SetErrorString("No such process.");
1867 }
1868
1869 FINISH:
1870 return args->m_error.Success();
1871}
1872
Chaoren Lin97ccc292015-02-03 01:51:12 +00001873Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001874NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1875{
1876 long ptrace_opts = 0;
1877
1878 // Have the child raise an event on exit. This is used to keep the child in
1879 // limbo until it is destroyed.
1880 ptrace_opts |= PTRACE_O_TRACEEXIT;
1881
1882 // Have the tracer trace threads which spawn in the inferior process.
1883 // TODO: if we want to support tracing the inferiors' child, add the
1884 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1885 ptrace_opts |= PTRACE_O_TRACECLONE;
1886
1887 // Have the tracer notify us before execve returns
1888 // (needed to disable legacy SIGTRAP generation)
1889 ptrace_opts |= PTRACE_O_TRACEEXEC;
1890
Chaoren Lin97ccc292015-02-03 01:51:12 +00001891 Error error;
1892 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1893 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001894}
1895
1896static ExitType convert_pid_status_to_exit_type (int status)
1897{
1898 if (WIFEXITED (status))
1899 return ExitType::eExitTypeExit;
1900 else if (WIFSIGNALED (status))
1901 return ExitType::eExitTypeSignal;
1902 else if (WIFSTOPPED (status))
1903 return ExitType::eExitTypeStop;
1904 else
1905 {
1906 // We don't know what this is.
1907 return ExitType::eExitTypeInvalid;
1908 }
1909}
1910
1911static int convert_pid_status_to_return_code (int status)
1912{
1913 if (WIFEXITED (status))
1914 return WEXITSTATUS (status);
1915 else if (WIFSIGNALED (status))
1916 return WTERMSIG (status);
1917 else if (WIFSTOPPED (status))
1918 return WSTOPSIG (status);
1919 else
1920 {
1921 // We don't know what this is.
1922 return ExitType::eExitTypeInvalid;
1923 }
1924}
1925
1926// Main process monitoring waitpid-loop handler.
1927bool
1928NativeProcessLinux::MonitorCallback(void *callback_baton,
1929 lldb::pid_t pid,
1930 bool exited,
1931 int signal,
1932 int status)
1933{
1934 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1935
1936 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1937 assert (process && "process is null");
1938 if (!process)
1939 {
1940 if (log)
1941 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1942 return true;
1943 }
1944
1945 // Certain activities differ based on whether the pid is the tid of the main thread.
1946 const bool is_main_thread = (pid == process->GetID ());
1947
1948 // Assume we keep monitoring by default.
1949 bool stop_monitoring = false;
1950
1951 // Handle when the thread exits.
1952 if (exited)
1953 {
1954 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001955 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 +00001956
1957 // This is a thread that exited. Ensure we're not tracking it anymore.
1958 const bool thread_found = process->StopTrackingThread (pid);
1959
Chaoren Linfa03ad22015-02-03 01:50:42 +00001960 // Make sure the thread state coordinator knows about this.
1961 process->NotifyThreadDeath (pid);
1962
Todd Fialaaf245d12014-06-30 21:05:18 +00001963 if (is_main_thread)
1964 {
1965 // We only set the exit status and notify the delegate if we haven't already set the process
1966 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1967 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001968 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001969 if (!already_notified)
1970 {
1971 if (log)
1972 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 ()));
1973 // The main thread exited. We're done monitoring. Report to delegate.
1974 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1975
1976 // Notify delegate that our process has exited.
1977 process->SetState (StateType::eStateExited, true);
1978 }
1979 else
1980 {
1981 if (log)
1982 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1983 }
1984 return true;
1985 }
1986 else
1987 {
1988 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1989 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1990 // and we would have done an all-stop then.
1991 if (log)
1992 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1993
1994 // Not the main thread, we keep going.
1995 return false;
1996 }
1997 }
1998
1999 // Get details on the signal raised.
2000 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002001 const auto err = process->GetSignalInfo(pid, &info);
2002 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002003 {
2004 // We have retrieved the signal info. Dispatch appropriately.
2005 if (info.si_signo == SIGTRAP)
2006 process->MonitorSIGTRAP(&info, pid);
2007 else
2008 process->MonitorSignal(&info, pid, exited);
2009
2010 stop_monitoring = false;
2011 }
2012 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002013 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002014 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002015 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002016 // This is a group stop reception for this tid.
2017 if (log)
2018 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2019 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002020 }
2021 else
2022 {
2023 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2024
2025 // A return value of ESRCH means the thread/process is no longer on the system,
2026 // so it was killed somehow outside of our control. Either way, we can't do anything
2027 // with it anymore.
2028
2029 // We stop monitoring if it was the main thread.
2030 stop_monitoring = is_main_thread;
2031
2032 // Stop tracking the metadata for the thread since it's entirely off the system now.
2033 const bool thread_found = process->StopTrackingThread (pid);
2034
Chaoren Linfa03ad22015-02-03 01:50:42 +00002035 // Make sure the thread state coordinator knows about this.
2036 process->NotifyThreadDeath (pid);
2037
Todd Fialaaf245d12014-06-30 21:05:18 +00002038 if (log)
2039 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002040 __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 +00002041
2042 if (is_main_thread)
2043 {
2044 // Notify the delegate - our process is not available but appears to have been killed outside
2045 // our control. Is eStateExited the right exit state in this case?
2046 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2047 process->SetState (StateType::eStateExited, true);
2048 }
2049 else
2050 {
2051 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2052 if (log)
2053 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);
2054 }
2055 }
2056 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002057
2058 return stop_monitoring;
2059}
2060
2061void
2062NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2063{
2064 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2065 const bool is_main_thread = (pid == GetID ());
2066
2067 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2068 if (!info)
2069 return;
2070
2071 // See if we can find a thread for this signal.
2072 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2073 if (!thread_sp)
2074 {
2075 if (log)
2076 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2077 }
2078
2079 switch (info->si_code)
2080 {
2081 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2082 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2083 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2084
2085 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2086 {
2087 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2088
Chaoren Linfa03ad22015-02-03 01:50:42 +00002089 // The main thread is stopped here.
2090 if (thread_sp)
2091 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2092 NotifyThreadStop (pid);
2093
Todd Fialaaf245d12014-06-30 21:05:18 +00002094 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002095 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002096 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002097 tid = static_cast<lldb::tid_t> (event_message);
2098 if (log)
2099 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002100
Chaoren Linfa03ad22015-02-03 01:50:42 +00002101 // If we don't track the thread yet: create it, mark as stopped.
2102 // If we do track it, this is the wait we needed. Now resume the new thread.
2103 // In all cases, resume the current (i.e. main process) thread.
2104 bool created_now = false;
2105 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2106 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2107
2108 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2109 if (!created_now)
2110 {
2111 // We can now resume the newly created thread since it is fully created.
2112 NotifyThreadCreateStopped (tid);
2113 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002114 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002115 {
2116 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetRunning ();
2117 Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2118 },
2119 CoordinatorErrorHandler);
2120 }
2121 else
2122 {
2123 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2124 // this thread is ready to go.
2125 reinterpret_cast<NativeThreadLinux*> (new_thread_sp.get ())->SetLaunching ();
2126 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002127 }
2128 else
2129 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002130 if (log)
2131 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 +00002132 }
2133
2134 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002135 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002136 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002137 {
2138 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2139 Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2140 },
2141 CoordinatorErrorHandler);
2142
Todd Fialaaf245d12014-06-30 21:05:18 +00002143 break;
2144 }
2145
2146 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002147 {
2148 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002149 if (log)
2150 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002151
Chaoren Linfa03ad22015-02-03 01:50:42 +00002152 // The thread state coordinator needs to reset due to the exec.
2153 m_coordinator_up->ResetForExec ();
2154
2155 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002156 {
2157 Mutex::Locker locker (m_threads_mutex);
2158
2159 if (log)
2160 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2161
2162 for (auto thread_sp : m_threads)
2163 {
2164 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2165 if (is_main_thread)
2166 {
2167 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 ());
2170 }
2171 else
2172 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002173 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002174 if (log)
2175 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2176 }
2177 }
2178
2179 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 }
2194
Chaoren Linfa03ad22015-02-03 01:50:42 +00002195 // Tell coordinator about about the "new" (since exec) stopped main thread.
2196 const lldb::tid_t main_thread_tid = GetID ();
2197 NotifyThreadCreateStopped (main_thread_tid);
2198
2199 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2200 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002201 // Let our delegate know we have just exec'd.
2202 NotifyDidExec ();
2203
2204 // If we have a main thread, indicate we are stopped.
2205 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002206
2207 // Let the process know we're stopped.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002208 SetState (StateType::eStateStopped);
2209
Todd Fialaaf245d12014-06-30 21:05:18 +00002210 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002211 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002212
2213 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2214 {
2215 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002216
2217 // This thread is currently stopped. It's not actually dead yet, just about to be.
2218 NotifyThreadStop (pid);
2219
Todd Fialaaf245d12014-06-30 21:05:18 +00002220 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002221 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002222 data = -1;
2223
2224 if (log)
2225 {
2226 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2227 __FUNCTION__,
2228 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2229 pid,
2230 is_main_thread ? "is main thread" : "not main thread");
2231 }
2232
Todd Fialaaf245d12014-06-30 21:05:18 +00002233 if (is_main_thread)
2234 {
2235 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002236 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002237
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002238 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002239 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002240 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002241 {
2242 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002243 Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002244 },
2245 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002246
2247 break;
2248 }
2249
2250 case 0:
2251 case TRAP_TRACE:
2252 // We receive this on single stepping.
2253 if (log)
2254 log->Printf ("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", __FUNCTION__, pid);
2255
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002256 if (thread_sp)
2257 {
2258 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2259 }
2260
Chaoren Linfa03ad22015-02-03 01:50:42 +00002261 // This thread is currently stopped.
2262 NotifyThreadStop (pid);
2263
Chaoren Linae29d392015-02-03 01:50:46 +00002264 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2265 // This would have already happened at the time the Resume() with step operation was signaled.
2266 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2267 // once all running threads have checked in as stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002268 SetCurrentThreadID (pid);
2269 // Tell the process we have a stop (from software breakpoint).
2270 SetState (StateType::eStateStopped, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002271 break;
2272
2273 case SI_KERNEL:
2274 case TRAP_BRKPT:
2275 if (log)
2276 log->Printf ("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2277
Chaoren Linfa03ad22015-02-03 01:50:42 +00002278 // This thread is currently stopped.
2279 NotifyThreadStop (pid);
2280
Todd Fialaaf245d12014-06-30 21:05:18 +00002281 // Mark the thread as stopped at breakpoint.
2282 if (thread_sp)
2283 {
2284 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2285 Error error = FixupBreakpointPCAsNeeded (thread_sp);
2286 if (error.Fail ())
2287 {
2288 if (log)
2289 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", __FUNCTION__, pid, error.AsCString ());
2290 }
2291 }
2292 else
2293 {
2294 if (log)
2295 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": warning, cannot process software breakpoint since no thread metadata", __FUNCTION__, pid);
2296 }
2297
2298
Chaoren Linfa03ad22015-02-03 01:50:42 +00002299 // We need to tell all other running threads before we notify the delegate about this stop.
2300 CallAfterRunningThreadsStop (pid,
2301 [=](lldb::tid_t deferred_notification_tid)
2302 {
2303 SetCurrentThreadID (deferred_notification_tid);
2304 // Tell the process we have a stop (from software breakpoint).
2305 SetState (StateType::eStateStopped, true);
2306 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002307 break;
2308
2309 case TRAP_HWBKPT:
2310 if (log)
2311 log->Printf ("NativeProcessLinux::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2312
Chaoren Linfa03ad22015-02-03 01:50:42 +00002313 // This thread is currently stopped.
2314 NotifyThreadStop (pid);
2315
Todd Fialaaf245d12014-06-30 21:05:18 +00002316 // Mark the thread as stopped at watchpoint.
2317 // The address is at (lldb::addr_t)info->si_addr if we need it.
2318 if (thread_sp)
2319 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2320 else
2321 {
2322 if (log)
2323 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ": warning, cannot process hardware breakpoint since no thread metadata", __FUNCTION__, GetID (), pid);
2324 }
2325
Chaoren Linfa03ad22015-02-03 01:50:42 +00002326 // We need to tell all other running threads before we notify the delegate about this stop.
2327 CallAfterRunningThreadsStop (pid,
2328 [=](lldb::tid_t deferred_notification_tid)
2329 {
2330 SetCurrentThreadID (deferred_notification_tid);
2331 // Tell the process we have a stop (from hardware breakpoint).
2332 SetState (StateType::eStateStopped, true);
2333 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002334 break;
2335
2336 case SIGTRAP:
2337 case (SIGTRAP | 0x80):
2338 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002339 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2340
2341 // This thread is currently stopped.
2342 NotifyThreadStop (pid);
2343 if (thread_sp)
2344 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2345
2346
Todd Fialaaf245d12014-06-30 21:05:18 +00002347 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002348 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002349 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002350 {
2351 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2352 Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2353 },
2354 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002355 break;
2356
2357 default:
2358 assert(false && "Unexpected SIGTRAP code!");
2359 if (log)
2360 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)));
2361 break;
2362
2363 }
2364}
2365
2366void
2367NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2368{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002369 assert (info && "null info");
2370 if (!info)
2371 return;
2372
2373 const int signo = info->si_signo;
2374 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002375
2376 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2377
2378 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2379 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2380 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2381 //
2382 // IOW, user generated signals never generate what we consider to be a
2383 // "crash".
2384 //
2385 // Similarly, ACK signals generated by this monitor.
2386
2387 // See if we can find a thread for this signal.
2388 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2389 if (!thread_sp)
2390 {
2391 if (log)
2392 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2393 }
2394
2395 // Handle the signal.
2396 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2397 {
2398 if (log)
2399 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2400 __FUNCTION__,
2401 GetUnixSignals ().GetSignalAsCString (signo),
2402 signo,
2403 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2404 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002405 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002406 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002407 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002408
Todd Fiala58a2f662014-08-12 17:02:07 +00002409 // Check for new thread notification.
2410 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2411 {
2412 // A new thread creation is being signaled. This is one of two parts that come in
2413 // a non-deterministic order. pid is the thread id.
2414 if (log)
2415 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2416 __FUNCTION__, GetID (), pid);
2417
2418 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002419 bool created_now = false;
2420 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002421 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2422
2423 // 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 +00002424 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002425 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002426 // We can now resume the newly created thread since it is fully created.
2427 NotifyThreadCreateStopped (pid);
2428 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002429 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002430 {
2431 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2432 Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2433 },
2434 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002435 }
2436 else
2437 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002438 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2439 // this thread is ready to go.
2440 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002441 }
2442
Todd Fiala58a2f662014-08-12 17:02:07 +00002443 // Done handling.
2444 return;
2445 }
2446
2447 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002448 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002449 {
2450 // This is a tgkill()-based stop.
2451 if (thread_sp)
2452 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002453 if (log)
2454 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2455 __FUNCTION__,
2456 GetID (),
2457 pid);
2458
Chaoren Linaab58632015-02-03 01:50:57 +00002459 // Check that we're not already marked with a stop reason.
2460 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2461 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2462 // and that, without an intervening resume, we received another stop. It is more likely
2463 // that we are missing the marking of a run state somewhere if we find that the thread was
2464 // marked as stopped.
2465 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ());
2466 assert (linux_thread_p && "linux_thread_p is null!");
2467
2468 const StateType thread_state = linux_thread_p->GetState ();
2469 if (!StateIsStoppedState (thread_state, false))
2470 {
2471 // An inferior thread just stopped, but was not the primary cause of the process stop.
2472 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2473 // stop signal as 0 to let lldb know this isn't the important stop.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002474 linux_thread_p->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002475 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002476 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002477 }
2478 else
2479 {
2480 if (log)
2481 {
2482 // Retrieve the signal name if the thread was stopped by a signal.
2483 int stop_signo = 0;
2484 const bool stopped_by_signal = linux_thread_p->IsStopped (&stop_signo);
2485 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2486 if (!signal_name)
2487 signal_name = "<no-signal-name>";
2488
2489 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",
2490 __FUNCTION__,
2491 GetID (),
2492 linux_thread_p->GetID (),
2493 StateAsCString (thread_state),
2494 stop_signo,
2495 signal_name);
2496 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002497 // Tell the thread state coordinator about the stop.
2498 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002499 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002500 }
2501
2502 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002503 return;
2504 }
2505
2506 if (log)
2507 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2508
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002509 // This thread is stopped.
2510 NotifyThreadStop (pid);
2511
Todd Fialaaf245d12014-06-30 21:05:18 +00002512 switch (signo)
2513 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002514 case SIGSTOP:
2515 {
2516 if (log)
2517 {
2518 if (is_from_llgs)
2519 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2520 else
2521 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2522 }
2523
Chaoren Linfa03ad22015-02-03 01:50:42 +00002524 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2525 // This thread will get stopped again as part of the group-stop completion.
2526 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002527 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002528 {
2529 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2530 // Pass this signal number on to the inferior to handle.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002531 Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002532 },
2533 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002534 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002535 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002536 case SIGSEGV:
2537 case SIGILL:
2538 case SIGFPE:
2539 case SIGBUS:
2540 if (thread_sp)
2541 reinterpret_cast<NativeThreadLinux*>(thread_sp.get())->SetCrashedWithException(
2542 signo, reinterpret_cast<lldb::addr_t>(info->si_addr));
2543 break;
2544 default:
2545 // This is just a pre-signal-delivery notification of the incoming signal.
2546 if (thread_sp)
2547 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2548
2549 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002550 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002551
2552 // Send a stop to the debugger after we get all other threads to stop.
2553 CallAfterRunningThreadsStop (pid,
2554 [=] (lldb::tid_t signaling_tid)
2555 {
2556 SetCurrentThreadID (signaling_tid);
2557 SetState (StateType::eStateStopped, true);
2558 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002559}
2560
2561Error
2562NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2563{
2564 Error error;
2565
2566 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2567 if (log)
2568 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2569
Chaoren Lin03f12d62015-02-03 01:50:49 +00002570 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2571 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002572 int deferred_signo = 0;
2573 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin03f12d62015-02-03 01:50:49 +00002574 int resume_count = 0;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002575 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002576
Chaoren Lin03f12d62015-02-03 01:50:49 +00002577
2578 // std::vector<NativeThreadProtocolSP> new_stop_threads;
Todd Fialaaf245d12014-06-30 21:05:18 +00002579
Chaoren Linfa03ad22015-02-03 01:50:42 +00002580 // Scope for threads mutex.
Todd Fialaaf245d12014-06-30 21:05:18 +00002581 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002582 Mutex::Locker locker (m_threads_mutex);
2583 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002584 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002585 assert (thread_sp && "thread list should not contain NULL threads");
Todd Fialaaf245d12014-06-30 21:05:18 +00002586
Chaoren Linfa03ad22015-02-03 01:50:42 +00002587 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2588 assert (action && "NULL ResumeAction returned for thread during Resume ()");
Todd Fialaaf245d12014-06-30 21:05:18 +00002589
Chaoren Linfa03ad22015-02-03 01:50:42 +00002590 if (log)
Todd Fialaaf245d12014-06-30 21:05:18 +00002591 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002592 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2593 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002594 }
2595
Chaoren Linfa03ad22015-02-03 01:50:42 +00002596 switch (action->state)
2597 {
2598 case eStateRunning:
2599 {
2600 // Run the thread, possibly feeding it the signal.
2601 const int signo = action->signal;
Chaoren Linb8af31d2015-02-03 01:50:51 +00002602 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002603 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linb8af31d2015-02-03 01:50:51 +00002604 {
2605 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2606 // Pass this signal number on to the inferior to handle.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002607 Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linb8af31d2015-02-03 01:50:51 +00002608 },
2609 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002610 ++resume_count;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002611 break;
2612 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002613
Chaoren Linfa03ad22015-02-03 01:50:42 +00002614 case eStateStepping:
Chaoren Linae29d392015-02-03 01:50:46 +00002615 {
2616 // Request the step.
2617 const int signo = action->signal;
2618 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002619 [=](lldb::tid_t tid_to_step, bool supress_signal)
Chaoren Linae29d392015-02-03 01:50:46 +00002620 {
2621 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStepping ();
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002622 auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linae29d392015-02-03 01:50:46 +00002623 assert (step_result && "SingleStep() failed");
2624 },
2625 CoordinatorErrorHandler);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002626 stepping = true;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002627 break;
Chaoren Linae29d392015-02-03 01:50:46 +00002628 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002629
2630 case eStateSuspended:
2631 case eStateStopped:
Chaoren Linae29d392015-02-03 01:50:46 +00002632 // if we haven't chosen a deferred signal tid yet, use this one.
2633 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
2634 {
2635 deferred_signal_tid = thread_sp->GetID ();
2636 deferred_signal_thread_sp = thread_sp;
2637 deferred_signo = SIGSTOP;
2638 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002639 break;
2640
2641 default:
2642 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2643 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2644 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002645 }
2646 }
2647
Chaoren Linfa03ad22015-02-03 01:50:42 +00002648 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2649 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002650 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2651 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002652 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002653 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2654 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002655 [=](lldb::tid_t deferred_notification_tid)
2656 {
Chaoren Linae29d392015-02-03 01:50:46 +00002657 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002658 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002659
2660 // Set the thread state as stopped by the deferred signo.
2661 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (deferred_signo);
2662
2663 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002664 SetState (StateType::eStateStopped, true);
2665 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002666 }
2667
2668 return error;
2669}
2670
2671Error
2672NativeProcessLinux::Halt ()
2673{
2674 Error error;
2675
Todd Fialaaf245d12014-06-30 21:05:18 +00002676 if (kill (GetID (), SIGSTOP) != 0)
2677 error.SetErrorToErrno ();
2678
2679 return error;
2680}
2681
2682Error
2683NativeProcessLinux::Detach ()
2684{
2685 Error error;
2686
2687 // Tell ptrace to detach from the process.
2688 if (GetID () != LLDB_INVALID_PROCESS_ID)
2689 error = Detach (GetID ());
2690
2691 // Stop monitoring the inferior.
2692 StopMonitor ();
2693
2694 // No error.
2695 return error;
2696}
2697
2698Error
2699NativeProcessLinux::Signal (int signo)
2700{
2701 Error error;
2702
2703 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2704 if (log)
2705 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2706 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2707
2708 if (kill(GetID(), signo))
2709 error.SetErrorToErrno();
2710
2711 return error;
2712}
2713
2714Error
Chaoren Line9547b82015-02-03 01:51:00 +00002715NativeProcessLinux::Interrupt ()
2716{
2717 // Pick a running thread (or if none, a not-dead stopped thread) as
2718 // the chosen thread that will be the stop-reason thread.
2719 Error error;
2720 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2721
2722 NativeThreadProtocolSP running_thread_sp;
2723 NativeThreadProtocolSP stopped_thread_sp;
2724 {
2725 Mutex::Locker locker (m_threads_mutex);
2726
2727 if (log)
2728 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2729
2730 for (auto thread_sp : m_threads)
2731 {
2732 // The thread shouldn't be null but lets just cover that here.
2733 if (!thread_sp)
2734 continue;
2735
2736 // If we have a running or stepping thread, we'll call that the
2737 // target of the interrupt.
2738 const auto thread_state = thread_sp->GetState ();
2739 if (thread_state == eStateRunning ||
2740 thread_state == eStateStepping)
2741 {
2742 running_thread_sp = thread_sp;
2743 break;
2744 }
2745 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2746 {
2747 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2748 stopped_thread_sp = thread_sp;
2749 }
2750 }
2751 }
2752
2753 if (!running_thread_sp && !stopped_thread_sp)
2754 {
2755 error.SetErrorString ("found no running/stepping or live stopped threads as target for interrupt");
2756 if (log)
2757 {
2758 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
2759 }
2760 return error;
2761 }
2762
2763 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2764
2765 if (log)
2766 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2767 __FUNCTION__,
2768 GetID (),
2769 running_thread_sp ? "running" : "stopped",
2770 deferred_signal_thread_sp->GetID ());
2771
2772 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2773 [=](lldb::tid_t deferred_notification_tid)
2774 {
2775 // Set the signal thread to the current thread.
2776 SetCurrentThreadID (deferred_notification_tid);
2777
2778 // Set the thread state as stopped by the deferred signo.
2779 reinterpret_cast<NativeThreadLinux*> (deferred_signal_thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
2780
2781 // Tell the process delegate that the process is in a stopped state.
2782 SetState (StateType::eStateStopped, true);
2783 });
2784 return error;
2785}
2786
2787Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002788NativeProcessLinux::Kill ()
2789{
2790 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2791 if (log)
2792 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2793
2794 Error error;
2795
2796 switch (m_state)
2797 {
2798 case StateType::eStateInvalid:
2799 case StateType::eStateExited:
2800 case StateType::eStateCrashed:
2801 case StateType::eStateDetached:
2802 case StateType::eStateUnloaded:
2803 // Nothing to do - the process is already dead.
2804 if (log)
2805 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2806 return error;
2807
2808 case StateType::eStateConnected:
2809 case StateType::eStateAttaching:
2810 case StateType::eStateLaunching:
2811 case StateType::eStateStopped:
2812 case StateType::eStateRunning:
2813 case StateType::eStateStepping:
2814 case StateType::eStateSuspended:
2815 // We can try to kill a process in these states.
2816 break;
2817 }
2818
2819 if (kill (GetID (), SIGKILL) != 0)
2820 {
2821 error.SetErrorToErrno ();
2822 return error;
2823 }
2824
2825 return error;
2826}
2827
2828static Error
2829ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2830{
2831 memory_region_info.Clear();
2832
2833 StringExtractor line_extractor (maps_line.c_str ());
2834
2835 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2836 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2837
2838 // Parse out the starting address
2839 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2840
2841 // Parse out hyphen separating start and end address from range.
2842 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2843 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2844
2845 // Parse out the ending address
2846 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2847
2848 // Parse out the space after the address.
2849 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2850 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2851
2852 // Save the range.
2853 memory_region_info.GetRange ().SetRangeBase (start_address);
2854 memory_region_info.GetRange ().SetRangeEnd (end_address);
2855
2856 // Parse out each permission entry.
2857 if (line_extractor.GetBytesLeft () < 4)
2858 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2859
2860 // Handle read permission.
2861 const char read_perm_char = line_extractor.GetChar ();
2862 if (read_perm_char == 'r')
2863 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2864 else
2865 {
2866 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2867 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2868 }
2869
2870 // Handle write permission.
2871 const char write_perm_char = line_extractor.GetChar ();
2872 if (write_perm_char == 'w')
2873 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2874 else
2875 {
2876 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2877 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2878 }
2879
2880 // Handle execute permission.
2881 const char exec_perm_char = line_extractor.GetChar ();
2882 if (exec_perm_char == 'x')
2883 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2884 else
2885 {
2886 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2887 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2888 }
2889
2890 return Error ();
2891}
2892
2893Error
2894NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2895{
2896 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2897 // with no perms if it is not mapped.
2898
2899 // Use an approach that reads memory regions from /proc/{pid}/maps.
2900 // Assume proc maps entries are in ascending order.
2901 // FIXME assert if we find differently.
2902 Mutex::Locker locker (m_mem_region_cache_mutex);
2903
2904 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2905 Error error;
2906
2907 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2908 {
2909 // We're done.
2910 error.SetErrorString ("unsupported");
2911 return error;
2912 }
2913
2914 // If our cache is empty, pull the latest. There should always be at least one memory region
2915 // if memory region handling is supported.
2916 if (m_mem_region_cache.empty ())
2917 {
2918 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2919 [&] (const std::string &line) -> bool
2920 {
2921 MemoryRegionInfo info;
2922 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2923 if (parse_error.Success ())
2924 {
2925 m_mem_region_cache.push_back (info);
2926 return true;
2927 }
2928 else
2929 {
2930 if (log)
2931 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2932 return false;
2933 }
2934 });
2935
2936 // If we had an error, we'll mark unsupported.
2937 if (error.Fail ())
2938 {
2939 m_supports_mem_region = LazyBool::eLazyBoolNo;
2940 return error;
2941 }
2942 else if (m_mem_region_cache.empty ())
2943 {
2944 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2945 // is supported. Assume we don't support map entries via procfs.
2946 if (log)
2947 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2948 m_supports_mem_region = LazyBool::eLazyBoolNo;
2949 error.SetErrorString ("not supported");
2950 return error;
2951 }
2952
2953 if (log)
2954 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2955
2956 // We support memory retrieval, remember that.
2957 m_supports_mem_region = LazyBool::eLazyBoolYes;
2958 }
2959 else
2960 {
2961 if (log)
2962 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2963 }
2964
2965 lldb::addr_t prev_base_address = 0;
2966
2967 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2968 // There can be a ton of regions on pthreads apps with lots of threads.
2969 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2970 {
2971 MemoryRegionInfo &proc_entry_info = *it;
2972
2973 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2974 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2975 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2976
2977 // If the target address comes before this entry, indicate distance to next region.
2978 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2979 {
2980 range_info.GetRange ().SetRangeBase (load_addr);
2981 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2982 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2983 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2984 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2985
2986 return error;
2987 }
2988 else if (proc_entry_info.GetRange ().Contains (load_addr))
2989 {
2990 // The target address is within the memory region we're processing here.
2991 range_info = proc_entry_info;
2992 return error;
2993 }
2994
2995 // The target memory address comes somewhere after the region we just parsed.
2996 }
2997
2998 // If we made it here, we didn't find an entry that contained the given address.
2999 error.SetErrorString ("address comes after final region");
3000
3001 if (log)
3002 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3003
3004 return error;
3005}
3006
3007void
3008NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3009{
3010 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3011 if (log)
3012 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3013
3014 {
3015 Mutex::Locker locker (m_mem_region_cache_mutex);
3016 if (log)
3017 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3018 m_mem_region_cache.clear ();
3019 }
3020}
3021
3022Error
3023NativeProcessLinux::AllocateMemory (
3024 lldb::addr_t size,
3025 uint32_t permissions,
3026 lldb::addr_t &addr)
3027{
3028 // FIXME implementing this requires the equivalent of
3029 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3030 // functional ThreadPlans working with Native*Protocol.
3031#if 1
3032 return Error ("not implemented yet");
3033#else
3034 addr = LLDB_INVALID_ADDRESS;
3035
3036 unsigned prot = 0;
3037 if (permissions & lldb::ePermissionsReadable)
3038 prot |= eMmapProtRead;
3039 if (permissions & lldb::ePermissionsWritable)
3040 prot |= eMmapProtWrite;
3041 if (permissions & lldb::ePermissionsExecutable)
3042 prot |= eMmapProtExec;
3043
3044 // TODO implement this directly in NativeProcessLinux
3045 // (and lift to NativeProcessPOSIX if/when that class is
3046 // refactored out).
3047 if (InferiorCallMmap(this, addr, 0, size, prot,
3048 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3049 m_addr_to_mmap_size[addr] = size;
3050 return Error ();
3051 } else {
3052 addr = LLDB_INVALID_ADDRESS;
3053 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3054 }
3055#endif
3056}
3057
3058Error
3059NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3060{
3061 // FIXME see comments in AllocateMemory - required lower-level
3062 // bits not in place yet (ThreadPlans)
3063 return Error ("not implemented");
3064}
3065
3066lldb::addr_t
3067NativeProcessLinux::GetSharedLibraryInfoAddress ()
3068{
3069#if 1
3070 // punt on this for now
3071 return LLDB_INVALID_ADDRESS;
3072#else
3073 // Return the image info address for the exe module
3074#if 1
3075 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3076
3077 ModuleSP module_sp;
3078 Error error = GetExeModuleSP (module_sp);
3079 if (error.Fail ())
3080 {
3081 if (log)
3082 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3083 return LLDB_INVALID_ADDRESS;
3084 }
3085
3086 if (module_sp == nullptr)
3087 {
3088 if (log)
3089 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3090 return LLDB_INVALID_ADDRESS;
3091 }
3092
3093 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3094 if (object_file_sp == nullptr)
3095 {
3096 if (log)
3097 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3098 return LLDB_INVALID_ADDRESS;
3099 }
3100
3101 return obj_file_sp->GetImageInfoAddress();
3102#else
3103 Target *target = &GetTarget();
3104 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3105 Address addr = obj_file->GetImageInfoAddress(target);
3106
3107 if (addr.IsValid())
3108 return addr.GetLoadAddress(target);
3109 return LLDB_INVALID_ADDRESS;
3110#endif
3111#endif // punt on this for now
3112}
3113
3114size_t
3115NativeProcessLinux::UpdateThreads ()
3116{
3117 // The NativeProcessLinux monitoring threads are always up to date
3118 // with respect to thread state and they keep the thread list
3119 // populated properly. All this method needs to do is return the
3120 // thread count.
3121 Mutex::Locker locker (m_threads_mutex);
3122 return m_threads.size ();
3123}
3124
3125bool
3126NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3127{
3128 arch = m_arch;
3129 return true;
3130}
3131
3132Error
3133NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3134{
3135 // FIXME put this behind a breakpoint protocol class that can be
3136 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003137 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003138 static const uint8_t g_i386_opcode [] = { 0xCC };
3139
3140 switch (m_arch.GetMachine ())
3141 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003142 case llvm::Triple::aarch64:
3143 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3144 return Error ();
3145
Todd Fialaaf245d12014-06-30 21:05:18 +00003146 case llvm::Triple::x86:
3147 case llvm::Triple::x86_64:
3148 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3149 return Error ();
3150
3151 default:
3152 assert(false && "CPU type not supported!");
3153 return Error ("CPU type not supported");
3154 }
3155}
3156
3157Error
3158NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3159{
3160 if (hardware)
3161 return Error ("NativeProcessLinux does not support hardware breakpoints");
3162 else
3163 return SetSoftwareBreakpoint (addr, size);
3164}
3165
3166Error
3167NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3168{
3169 // FIXME put this behind a breakpoint protocol class that can be
3170 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003171 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003172 static const uint8_t g_i386_opcode [] = { 0xCC };
3173
3174 switch (m_arch.GetMachine ())
3175 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003176 case llvm::Triple::aarch64:
3177 trap_opcode_bytes = g_aarch64_opcode;
3178 actual_opcode_size = sizeof(g_aarch64_opcode);
3179 return Error ();
3180
Todd Fialaaf245d12014-06-30 21:05:18 +00003181 case llvm::Triple::x86:
3182 case llvm::Triple::x86_64:
3183 trap_opcode_bytes = g_i386_opcode;
3184 actual_opcode_size = sizeof(g_i386_opcode);
3185 return Error ();
3186
3187 default:
3188 assert(false && "CPU type not supported!");
3189 return Error ("CPU type not supported");
3190 }
3191}
3192
3193#if 0
3194ProcessMessage::CrashReason
3195NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3196{
3197 ProcessMessage::CrashReason reason;
3198 assert(info->si_signo == SIGSEGV);
3199
3200 reason = ProcessMessage::eInvalidCrashReason;
3201
3202 switch (info->si_code)
3203 {
3204 default:
3205 assert(false && "unexpected si_code for SIGSEGV");
3206 break;
3207 case SI_KERNEL:
3208 // Linux will occasionally send spurious SI_KERNEL codes.
3209 // (this is poorly documented in sigaction)
3210 // One way to get this is via unaligned SIMD loads.
3211 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3212 break;
3213 case SEGV_MAPERR:
3214 reason = ProcessMessage::eInvalidAddress;
3215 break;
3216 case SEGV_ACCERR:
3217 reason = ProcessMessage::ePrivilegedAddress;
3218 break;
3219 }
3220
3221 return reason;
3222}
3223#endif
3224
3225
3226#if 0
3227ProcessMessage::CrashReason
3228NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3229{
3230 ProcessMessage::CrashReason reason;
3231 assert(info->si_signo == SIGILL);
3232
3233 reason = ProcessMessage::eInvalidCrashReason;
3234
3235 switch (info->si_code)
3236 {
3237 default:
3238 assert(false && "unexpected si_code for SIGILL");
3239 break;
3240 case ILL_ILLOPC:
3241 reason = ProcessMessage::eIllegalOpcode;
3242 break;
3243 case ILL_ILLOPN:
3244 reason = ProcessMessage::eIllegalOperand;
3245 break;
3246 case ILL_ILLADR:
3247 reason = ProcessMessage::eIllegalAddressingMode;
3248 break;
3249 case ILL_ILLTRP:
3250 reason = ProcessMessage::eIllegalTrap;
3251 break;
3252 case ILL_PRVOPC:
3253 reason = ProcessMessage::ePrivilegedOpcode;
3254 break;
3255 case ILL_PRVREG:
3256 reason = ProcessMessage::ePrivilegedRegister;
3257 break;
3258 case ILL_COPROC:
3259 reason = ProcessMessage::eCoprocessorError;
3260 break;
3261 case ILL_BADSTK:
3262 reason = ProcessMessage::eInternalStackError;
3263 break;
3264 }
3265
3266 return reason;
3267}
3268#endif
3269
3270#if 0
3271ProcessMessage::CrashReason
3272NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3273{
3274 ProcessMessage::CrashReason reason;
3275 assert(info->si_signo == SIGFPE);
3276
3277 reason = ProcessMessage::eInvalidCrashReason;
3278
3279 switch (info->si_code)
3280 {
3281 default:
3282 assert(false && "unexpected si_code for SIGFPE");
3283 break;
3284 case FPE_INTDIV:
3285 reason = ProcessMessage::eIntegerDivideByZero;
3286 break;
3287 case FPE_INTOVF:
3288 reason = ProcessMessage::eIntegerOverflow;
3289 break;
3290 case FPE_FLTDIV:
3291 reason = ProcessMessage::eFloatDivideByZero;
3292 break;
3293 case FPE_FLTOVF:
3294 reason = ProcessMessage::eFloatOverflow;
3295 break;
3296 case FPE_FLTUND:
3297 reason = ProcessMessage::eFloatUnderflow;
3298 break;
3299 case FPE_FLTRES:
3300 reason = ProcessMessage::eFloatInexactResult;
3301 break;
3302 case FPE_FLTINV:
3303 reason = ProcessMessage::eFloatInvalidOperation;
3304 break;
3305 case FPE_FLTSUB:
3306 reason = ProcessMessage::eFloatSubscriptRange;
3307 break;
3308 }
3309
3310 return reason;
3311}
3312#endif
3313
3314#if 0
3315ProcessMessage::CrashReason
3316NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3317{
3318 ProcessMessage::CrashReason reason;
3319 assert(info->si_signo == SIGBUS);
3320
3321 reason = ProcessMessage::eInvalidCrashReason;
3322
3323 switch (info->si_code)
3324 {
3325 default:
3326 assert(false && "unexpected si_code for SIGBUS");
3327 break;
3328 case BUS_ADRALN:
3329 reason = ProcessMessage::eIllegalAlignment;
3330 break;
3331 case BUS_ADRERR:
3332 reason = ProcessMessage::eIllegalAddress;
3333 break;
3334 case BUS_OBJERR:
3335 reason = ProcessMessage::eHardwareError;
3336 break;
3337 }
3338
3339 return reason;
3340}
3341#endif
3342
3343void
3344NativeProcessLinux::ServeOperation(OperationArgs *args)
3345{
3346 NativeProcessLinux *monitor = args->m_monitor;
3347
3348 // We are finised with the arguments and are ready to go. Sync with the
3349 // parent thread and start serving operations on the inferior.
3350 sem_post(&args->m_semaphore);
3351
3352 for(;;)
3353 {
3354 // wait for next pending operation
3355 if (sem_wait(&monitor->m_operation_pending))
3356 {
3357 if (errno == EINTR)
3358 continue;
3359 assert(false && "Unexpected errno from sem_wait");
3360 }
3361
3362 reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3363
3364 // notify calling thread that operation is complete
3365 sem_post(&monitor->m_operation_done);
3366 }
3367}
3368
3369void
3370NativeProcessLinux::DoOperation(void *op)
3371{
3372 Mutex::Locker lock(m_operation_mutex);
3373
3374 m_operation = op;
3375
3376 // notify operation thread that an operation is ready to be processed
3377 sem_post(&m_operation_pending);
3378
3379 // wait for operation to complete
3380 while (sem_wait(&m_operation_done))
3381 {
3382 if (errno == EINTR)
3383 continue;
3384 assert(false && "Unexpected errno from sem_wait");
3385 }
3386}
3387
3388Error
3389NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3390{
3391 ReadOperation op(addr, buf, size, bytes_read);
3392 DoOperation(&op);
3393 return op.GetError ();
3394}
3395
3396Error
3397NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3398{
3399 WriteOperation op(addr, buf, size, bytes_written);
3400 DoOperation(&op);
3401 return op.GetError ();
3402}
3403
Chaoren Lin97ccc292015-02-03 01:51:12 +00003404Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003405NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3406 uint32_t size, RegisterValue &value)
3407{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003408 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003409 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003410 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003411}
3412
Chaoren Lin97ccc292015-02-03 01:51:12 +00003413Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003414NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3415 const char* reg_name, const RegisterValue &value)
3416{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003417 WriteRegOperation 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::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3424{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003425 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003426 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003427 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003428}
3429
Chaoren Lin97ccc292015-02-03 01:51:12 +00003430Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003431NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3432{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003433 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003434 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003435 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003436}
3437
Chaoren Lin97ccc292015-02-03 01:51:12 +00003438Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003439NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3440{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003441 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003442 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003443 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003444}
3445
Chaoren Lin97ccc292015-02-03 01:51:12 +00003446Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003447NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3448{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003449 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003450 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003451 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003452}
3453
Chaoren Lin97ccc292015-02-03 01:51:12 +00003454Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003455NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3456{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003457 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003458 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003459 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003460}
3461
Chaoren Lin97ccc292015-02-03 01:51:12 +00003462Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003463NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3464{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003465 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003466 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003467 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003468}
3469
Chaoren Lin97ccc292015-02-03 01:51:12 +00003470Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003471NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3472{
Todd Fialaaf245d12014-06-30 21:05:18 +00003473 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3474
3475 if (log)
3476 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3477 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003478 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003479 DoOperation (&op);
3480 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003481 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3482 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003483}
3484
Chaoren Lin97ccc292015-02-03 01:51:12 +00003485Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003486NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3487{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003488 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003489 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003490 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003491}
3492
Chaoren Lin97ccc292015-02-03 01:51:12 +00003493Error
3494NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003495{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003496 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003497 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003498 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003499}
3500
Chaoren Lin97ccc292015-02-03 01:51:12 +00003501Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003502NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3503{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003504 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003505 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003506 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003507}
3508
3509lldb_private::Error
3510NativeProcessLinux::Detach(lldb::tid_t tid)
3511{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003512 if (tid == LLDB_INVALID_THREAD_ID)
3513 return Error();
3514
3515 DetachOperation op(tid);
3516 DoOperation(&op);
3517 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003518}
3519
3520bool
3521NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3522{
3523 int target_fd = open(path, flags, 0666);
3524
3525 if (target_fd == -1)
3526 return false;
3527
3528 return (dup2(target_fd, fd) == -1) ? false : true;
3529}
3530
3531void
3532NativeProcessLinux::StopMonitoringChildProcess()
3533{
Zachary Turneracee96a2014-09-23 18:32:09 +00003534 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003535 {
Zachary Turner39de3112014-09-09 20:54:56 +00003536 m_monitor_thread.Cancel();
3537 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003538 }
3539}
3540
3541void
3542NativeProcessLinux::StopMonitor()
3543{
3544 StopMonitoringChildProcess();
3545 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003546 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003547 sem_destroy(&m_operation_pending);
3548 sem_destroy(&m_operation_done);
3549
3550 // TODO: validate whether this still holds, fix up comment.
3551 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3552 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3553 // the descriptor to a ConnectionFileDescriptor object. Consequently
3554 // even though still has the file descriptor, we shouldn't close it here.
3555}
3556
3557void
3558NativeProcessLinux::StopOpThread()
3559{
Zachary Turneracee96a2014-09-23 18:32:09 +00003560 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003561 return;
3562
Zachary Turner39de3112014-09-09 20:54:56 +00003563 m_operation_thread.Cancel();
3564 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003565}
3566
Chaoren Linfa03ad22015-02-03 01:50:42 +00003567Error
3568NativeProcessLinux::StartCoordinatorThread ()
3569{
3570 Error error;
3571 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3572 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3573
3574 // Skip if thread is already running
3575 if (m_coordinator_thread.IsJoinable())
3576 {
3577 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3578 if (log)
3579 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3580 return error;
3581 }
3582
3583 // Enable verbose logging if lldb thread logging is enabled.
3584 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3585
3586 if (log)
3587 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3588 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3589 return error;
3590}
3591
3592void *
3593NativeProcessLinux::CoordinatorThread (void *arg)
3594{
3595 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3596
3597 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3598 assert (process && "null process passed to CoordinatorThread");
3599 if (!process)
3600 {
3601 if (log)
3602 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3603 return nullptr;
3604 }
3605
3606 // Run the thread state coordinator loop until it is done. This call uses
3607 // efficient waiting for an event to be ready.
3608 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3609 {
3610 }
3611
3612 if (log)
3613 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3614
3615 return nullptr;
3616}
3617
3618void
3619NativeProcessLinux::StopCoordinatorThread()
3620{
3621 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3622 if (log)
3623 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3624
3625 // Tell the coordinator we're done. This will cause the coordinator
3626 // run loop thread to exit when the processing queue hits this message.
3627 m_coordinator_up->StopCoordinator ();
3628}
3629
Todd Fialaaf245d12014-06-30 21:05:18 +00003630bool
3631NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3632{
3633 for (auto thread_sp : m_threads)
3634 {
3635 assert (thread_sp && "thread list should not contain NULL threads");
3636 if (thread_sp->GetID () == thread_id)
3637 {
3638 // We have this thread.
3639 return true;
3640 }
3641 }
3642
3643 // We don't have this thread.
3644 return false;
3645}
3646
3647NativeThreadProtocolSP
3648NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3649{
3650 // CONSIDER organize threads by map - we can do better than linear.
3651 for (auto thread_sp : m_threads)
3652 {
3653 if (thread_sp->GetID () == thread_id)
3654 return thread_sp;
3655 }
3656
3657 // We don't have this thread.
3658 return NativeThreadProtocolSP ();
3659}
3660
3661bool
3662NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3663{
3664 Mutex::Locker locker (m_threads_mutex);
3665 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3666 {
3667 if (*it && ((*it)->GetID () == thread_id))
3668 {
3669 m_threads.erase (it);
3670 return true;
3671 }
3672 }
3673
3674 // Didn't find it.
3675 return false;
3676}
3677
3678NativeThreadProtocolSP
3679NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3680{
3681 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3682
3683 Mutex::Locker locker (m_threads_mutex);
3684
3685 if (log)
3686 {
3687 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3688 __FUNCTION__,
3689 GetID (),
3690 thread_id);
3691 }
3692
3693 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3694
3695 // If this is the first thread, save it as the current thread
3696 if (m_threads.empty ())
3697 SetCurrentThreadID (thread_id);
3698
3699 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3700 m_threads.push_back (thread_sp);
3701
3702 return thread_sp;
3703}
3704
3705NativeThreadProtocolSP
3706NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3707{
3708 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3709
3710 Mutex::Locker locker (m_threads_mutex);
3711 if (log)
3712 {
3713 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3714 __FUNCTION__,
3715 GetID (),
3716 thread_id);
3717 }
3718
3719 // Retrieve the thread if it is already getting tracked.
3720 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3721 if (thread_sp)
3722 {
3723 if (log)
3724 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3725 __FUNCTION__,
3726 GetID (),
3727 thread_id);
3728 created = false;
3729 return thread_sp;
3730
3731 }
3732
3733 // Create the thread metadata since it isn't being tracked.
3734 if (log)
3735 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3736 __FUNCTION__,
3737 GetID (),
3738 thread_id);
3739
3740 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3741 m_threads.push_back (thread_sp);
3742 created = true;
3743
3744 return thread_sp;
3745}
3746
3747Error
3748NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3749{
Todd Fiala75f47c32014-10-11 21:42:09 +00003750 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003751
3752 Error error;
3753
3754 // Get a linux thread pointer.
3755 if (!thread_sp)
3756 {
3757 error.SetErrorString ("null thread_sp");
3758 if (log)
3759 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3760 return error;
3761 }
3762 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get());
3763
3764 // Find out the size of a breakpoint (might depend on where we are in the code).
3765 NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext ();
3766 if (!context_sp)
3767 {
3768 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3769 if (log)
3770 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3771 return error;
3772 }
3773
3774 uint32_t breakpoint_size = 0;
3775 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3776 if (error.Fail ())
3777 {
3778 if (log)
3779 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3780 return error;
3781 }
3782 else
3783 {
3784 if (log)
3785 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3786 }
3787
3788 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3789 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3790 lldb::addr_t breakpoint_addr = initial_pc_addr;
3791 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3792 {
3793 // Do not allow breakpoint probe to wrap around.
3794 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3795 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3796 }
3797
3798 // Check if we stopped because of a breakpoint.
3799 NativeBreakpointSP breakpoint_sp;
3800 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3801 if (!error.Success () || !breakpoint_sp)
3802 {
3803 // We didn't find one at a software probe location. Nothing to do.
3804 if (log)
3805 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3806 return Error ();
3807 }
3808
3809 // If the breakpoint is not a software breakpoint, nothing to do.
3810 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3811 {
3812 if (log)
3813 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3814 return Error ();
3815 }
3816
3817 //
3818 // We have a software breakpoint and need to adjust the PC.
3819 //
3820
3821 // Sanity check.
3822 if (breakpoint_size == 0)
3823 {
3824 // Nothing to do! How did we get here?
3825 if (log)
3826 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);
3827 return Error ();
3828 }
3829
3830 // Change the program counter.
3831 if (log)
3832 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);
3833
3834 error = context_sp->SetPC (breakpoint_addr);
3835 if (error.Fail ())
3836 {
3837 if (log)
3838 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ());
3839 return error;
3840 }
3841
3842 return error;
3843}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003844
3845void
3846NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3847{
3848 const bool is_stopped = true;
3849 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3850}
3851
3852void
3853NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3854{
3855 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3856}
3857
3858void
3859NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3860{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003861 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003862}
3863
3864void
3865NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3866 const std::function<void (lldb::tid_t tid)> &call_after_function)
3867{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003868 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3869 if (log)
3870 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3871
Chaoren Linfa03ad22015-02-03 01:50:42 +00003872 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003873 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003874 [=](lldb::tid_t request_stop_tid)
3875 {
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003876 RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003877 },
3878 call_after_function,
3879 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003880}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003881
Chaoren Lin03f12d62015-02-03 01:50:49 +00003882void
3883NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3884 lldb::tid_t skip_stop_request_tid,
3885 const std::function<void (lldb::tid_t tid)> &call_after_function)
3886{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003887 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3888 if (log)
3889 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3890
Chaoren Lin03f12d62015-02-03 01:50:49 +00003891 const lldb::pid_t pid = GetID ();
3892 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3893 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3894 [=](lldb::tid_t request_stop_tid)
3895 {
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003896 RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003897 },
3898 call_after_function,
3899 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003900}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003901
3902lldb_private::Error
3903NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3904{
3905 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3906 if (log)
3907 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3908
3909 Error err;
3910 errno = 0;
3911 if (::tgkill (pid, tid, SIGSTOP) != 0)
3912 {
3913 err.SetErrorToErrno ();
3914 if (log)
3915 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3916 }
3917
3918 return err;
3919}