blob: f740669af7784e737ab5b99c04ef125f6b9b2f14 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
21// C++ Includes
22#include <fstream>
23#include <string>
24
25// Other libraries and framework includes
26#include "lldb/Core/Debugger.h"
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000027#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Core/Error.h"
29#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000030#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Core/RegisterValue.h"
32#include "lldb/Core/Scalar.h"
33#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000034#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000035#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000036#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000037#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000038#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000039#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000041#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044#include "lldb/Utility/PseudoTerminal.h"
45
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000046#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000048#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049#include "NativeThreadLinux.h"
50#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000051#include "Procfs.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000052#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054// System includes - They have to be included after framework includes because they define some
55// macros which collide with variable names in other modules
56#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/personality.h>
58#include <sys/ptrace.h>
59#include <sys/socket.h>
60#include <sys/syscall.h>
61#include <sys/types.h>
62#include <sys/uio.h>
63#include <sys/user.h>
64#include <sys/wait.h>
65
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000066#if defined (__arm64__) || defined (__aarch64__)
67// NT_PRSTATUS and NT_FPREGSET definition
68#include <elf.h>
69#endif
70
Todd Fialacacde7d2014-09-27 16:54:22 +000071#ifdef __ANDROID__
72#define __ptrace_request int
73#define PT_DETACH PTRACE_DETACH
74#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000075
76#define DEBUG_PTRACE_MAXBYTES 20
77
78// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000079#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000080#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000081 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000082#endif
Todd Fialadda61942014-07-02 21:34:04 +000083#endif
84#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000085#ifndef PTRACE_SETREGS
86 #define PTRACE_SETREGS 13
87#endif
Todd Fialadda61942014-07-02 21:34:04 +000088#endif
89#ifndef PT_GETFPREGS
90#ifndef PTRACE_GETFPREGS
91 #define PTRACE_GETFPREGS 14
92#endif
93#endif
94#ifndef PT_SETFPREGS
95#ifndef PTRACE_SETFPREGS
96 #define PTRACE_SETFPREGS 15
97#endif
98#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000099#ifndef PTRACE_GETREGSET
100 #define PTRACE_GETREGSET 0x4204
101#endif
102#ifndef PTRACE_SETREGSET
103 #define PTRACE_SETREGSET 0x4205
104#endif
105#ifndef PTRACE_GET_THREAD_AREA
106 #define PTRACE_GET_THREAD_AREA 25
107#endif
108#ifndef PTRACE_ARCH_PRCTL
109 #define PTRACE_ARCH_PRCTL 30
110#endif
111#ifndef ARCH_GET_FS
112 #define ARCH_SET_GS 0x1001
113 #define ARCH_SET_FS 0x1002
114 #define ARCH_GET_FS 0x1003
115 #define ARCH_GET_GS 0x1004
116#endif
117
Todd Fiala0bce1b62014-08-17 00:10:50 +0000118#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000119
120// Support hardware breakpoints in case it has not been defined
121#ifndef TRAP_HWBKPT
122 #define TRAP_HWBKPT 4
123#endif
124
125// Try to define a macro to encapsulate the tgkill syscall
126// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000127#define tgkill(pid, tid, sig) \
128 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000129
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
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000140using namespace lldb;
141using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000142using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000143using namespace llvm;
144
Todd Fialaaf245d12014-06-30 21:05:18 +0000145// Private bits we only need internally.
146namespace
147{
Tamas Berghammer43f2d972015-03-04 11:10:03 +0000148 static void * const EXIT_OPERATION = nullptr;
149
Todd Fialaaf245d12014-06-30 21:05:18 +0000150 const UnixSignals&
151 GetUnixSignals ()
152 {
153 static process_linux::LinuxSignals signals;
154 return signals;
155 }
156
Chaoren Linfa03ad22015-02-03 01:50:42 +0000157 ThreadStateCoordinator::LogFunction
158 GetThreadLoggerFunction ()
159 {
160 return [](const char *format, va_list args)
161 {
162 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
163 if (log)
164 log->VAPrintf (format, args);
165 };
166 }
167
168 void
169 CoordinatorErrorHandler (const std::string &error_message)
170 {
171 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
172 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000173 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000174 assert (false && "ThreadStateCoordinator error reported");
175 }
176
Todd Fialaaf245d12014-06-30 21:05:18 +0000177 Error
178 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
179 {
180 // Grab process info for the running process.
181 ProcessInstanceInfo process_info;
182 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000183 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000184
185 // Resolve the executable module.
186 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000187 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000188 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
189 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000190 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000191 exe_module_sp,
192 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
193
194 if (!error.Success ())
195 return error;
196
197 // Check if we've got our architecture from the exe_module.
198 arch = exe_module_sp->GetArchitecture ();
199 if (arch.IsValid ())
200 return Error();
201 else
202 return Error("failed to retrieve a valid architecture from the exe module");
203 }
204
205 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000206 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000207 {
208 uint8_t *ptr = (uint8_t *)bytes;
209 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
210 for(uint32_t i=0; i<loop_count; i++)
211 {
212 s.Printf ("[%x]", *ptr);
213 ptr++;
214 }
215 }
216
217 void
218 PtraceDisplayBytes(int &req, void *data, size_t data_size)
219 {
220 StreamString buf;
221 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
222 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
223
224 if (verbose_log)
225 {
226 switch(req)
227 {
228 case PTRACE_POKETEXT:
229 {
230 DisplayBytes(buf, &data, 8);
231 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
232 break;
233 }
234 case PTRACE_POKEDATA:
235 {
236 DisplayBytes(buf, &data, 8);
237 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
238 break;
239 }
240 case PTRACE_POKEUSER:
241 {
242 DisplayBytes(buf, &data, 8);
243 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
244 break;
245 }
246 case PTRACE_SETREGS:
247 {
248 DisplayBytes(buf, data, data_size);
249 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
250 break;
251 }
252 case PTRACE_SETFPREGS:
253 {
254 DisplayBytes(buf, data, data_size);
255 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
256 break;
257 }
258 case PTRACE_SETSIGINFO:
259 {
260 DisplayBytes(buf, data, sizeof(siginfo_t));
261 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
262 break;
263 }
264 case PTRACE_SETREGSET:
265 {
266 // Extract iov_base from data, which is a pointer to the struct IOVEC
267 DisplayBytes(buf, *(void **)data, data_size);
268 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
269 break;
270 }
271 default:
272 {
273 }
274 }
275 }
276 }
277
278 // Wrapper for ptrace to catch errors and log calls.
279 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
280 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000281 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
282 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000283 {
284 long int result;
285
286 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
287
288 PtraceDisplayBytes(req, data, data_size);
289
Chaoren Lin97ccc292015-02-03 01:51:12 +0000290 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000291 errno = 0;
292 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000293 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000294 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000295 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000296
Chaoren Lin97ccc292015-02-03 01:51:12 +0000297 if (result == -1)
298 error.SetErrorToErrno();
299
Todd Fialaaf245d12014-06-30 21:05:18 +0000300 if (log)
301 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
302 reqName, pid, addr, data, data_size, result, file, line);
303
304 PtraceDisplayBytes(req, data, data_size);
305
Chaoren Lin97ccc292015-02-03 01:51:12 +0000306 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000307 {
308 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000309 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000310 {
311 case ESRCH: str = "ESRCH"; break;
312 case EINVAL: str = "EINVAL"; break;
313 case EBUSY: str = "EBUSY"; break;
314 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000315 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000316 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000317 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000318 }
319
320 return result;
321 }
322
323#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
324 // Wrapper for ptrace when logging is not required.
325 // Sets errno to 0 prior to calling ptrace.
326 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000327 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000328 {
329 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000330
331 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000332 errno = 0;
333 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000334 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000335 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000336 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000337
338 if (result == -1)
339 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000340 return result;
341 }
342#endif
343
344 //------------------------------------------------------------------------------
345 // Static implementations of NativeProcessLinux::ReadMemory and
346 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
347 // functions without needed to go thru the thread funnel.
348
Chaoren Lin97ccc292015-02-03 01:51:12 +0000349 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000350 DoReadMemory (
351 lldb::pid_t pid,
352 lldb::addr_t vm_addr,
353 void *buf,
354 lldb::addr_t size,
355 Error &error)
356 {
357 // ptrace word size is determined by the host, not the child
358 static const unsigned word_size = sizeof(void*);
359 unsigned char *dst = static_cast<unsigned char*>(buf);
360 lldb::addr_t bytes_read;
361 lldb::addr_t remainder;
362 long data;
363
364 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
365 if (log)
366 ProcessPOSIXLog::IncNestLevel();
367 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
368 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
369 pid, word_size, (void*)vm_addr, buf, size);
370
371 assert(sizeof(data) >= word_size);
372 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
373 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000374 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
375 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000376 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000377 if (log)
378 ProcessPOSIXLog::DecNestLevel();
379 return bytes_read;
380 }
381
382 remainder = size - bytes_read;
383 remainder = remainder > word_size ? word_size : remainder;
384
385 // Copy the data into our buffer
386 for (unsigned i = 0; i < remainder; ++i)
387 dst[i] = ((data >> i*8) & 0xFF);
388
389 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
390 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
391 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
392 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
393 {
394 uintptr_t print_dst = 0;
395 // Format bytes from data by moving into print_dst for log output
396 for (unsigned i = 0; i < remainder; ++i)
397 print_dst |= (((data >> i*8) & 0xFF) << i*8);
398 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
399 (void*)vm_addr, print_dst, (unsigned long)data);
400 }
401
402 vm_addr += word_size;
403 dst += word_size;
404 }
405
406 if (log)
407 ProcessPOSIXLog::DecNestLevel();
408 return bytes_read;
409 }
410
Chaoren Lin97ccc292015-02-03 01:51:12 +0000411 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000412 DoWriteMemory(
413 lldb::pid_t pid,
414 lldb::addr_t vm_addr,
415 const void *buf,
416 lldb::addr_t size,
417 Error &error)
418 {
419 // ptrace word size is determined by the host, not the child
420 static const unsigned word_size = sizeof(void*);
421 const unsigned char *src = static_cast<const unsigned char*>(buf);
422 lldb::addr_t bytes_written = 0;
423 lldb::addr_t remainder;
424
425 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
426 if (log)
427 ProcessPOSIXLog::IncNestLevel();
428 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
429 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
430 pid, word_size, (void*)vm_addr, buf, size);
431
432 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
433 {
434 remainder = size - bytes_written;
435 remainder = remainder > word_size ? word_size : remainder;
436
437 if (remainder == word_size)
438 {
439 unsigned long data = 0;
440 assert(sizeof(data) >= word_size);
441 for (unsigned i = 0; i < word_size; ++i)
442 data |= (unsigned long)src[i] << i*8;
443
444 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
446 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
447 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
448 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000449 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000450
Chaoren Lin97ccc292015-02-03 01:51:12 +0000451 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000453 if (log)
454 ProcessPOSIXLog::DecNestLevel();
455 return bytes_written;
456 }
457 }
458 else
459 {
460 unsigned char buff[8];
461 if (DoReadMemory(pid, vm_addr,
462 buff, word_size, error) != word_size)
463 {
464 if (log)
465 ProcessPOSIXLog::DecNestLevel();
466 return bytes_written;
467 }
468
469 memcpy(buff, src, remainder);
470
471 if (DoWriteMemory(pid, vm_addr,
472 buff, word_size, error) != word_size)
473 {
474 if (log)
475 ProcessPOSIXLog::DecNestLevel();
476 return bytes_written;
477 }
478
479 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
480 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
481 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
482 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
483 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000484 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000485 }
486
487 vm_addr += word_size;
488 src += word_size;
489 }
490 if (log)
491 ProcessPOSIXLog::DecNestLevel();
492 return bytes_written;
493 }
494
495 //------------------------------------------------------------------------------
496 /// @class Operation
497 /// @brief Represents a NativeProcessLinux operation.
498 ///
499 /// Under Linux, it is not possible to ptrace() from any other thread but the
500 /// one that spawned or attached to the process from the start. Therefore, when
501 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
502 /// process the operation must be "funneled" to a specific thread to perform the
503 /// task. The Operation class provides an abstract base for all services the
504 /// NativeProcessLinux must perform via the single virtual function Execute, thus
505 /// encapsulating the code that needs to run in the privileged context.
506 class Operation
507 {
508 public:
509 Operation () : m_error() { }
510
511 virtual
512 ~Operation() {}
513
514 virtual void
515 Execute (NativeProcessLinux *process) = 0;
516
517 const Error &
518 GetError () const { return m_error; }
519
520 protected:
521 Error m_error;
522 };
523
524 //------------------------------------------------------------------------------
525 /// @class ReadOperation
526 /// @brief Implements NativeProcessLinux::ReadMemory.
527 class ReadOperation : public Operation
528 {
529 public:
530 ReadOperation (
531 lldb::addr_t addr,
532 void *buff,
533 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000534 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000535 Operation (),
536 m_addr (addr),
537 m_buff (buff),
538 m_size (size),
539 m_result (result)
540 {
541 }
542
543 void Execute (NativeProcessLinux *process) override;
544
545 private:
546 lldb::addr_t m_addr;
547 void *m_buff;
548 lldb::addr_t m_size;
549 lldb::addr_t &m_result;
550 };
551
552 void
553 ReadOperation::Execute (NativeProcessLinux *process)
554 {
555 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
556 }
557
558 //------------------------------------------------------------------------------
559 /// @class WriteOperation
560 /// @brief Implements NativeProcessLinux::WriteMemory.
561 class WriteOperation : public Operation
562 {
563 public:
564 WriteOperation (
565 lldb::addr_t addr,
566 const void *buff,
567 lldb::addr_t size,
568 lldb::addr_t &result) :
569 Operation (),
570 m_addr (addr),
571 m_buff (buff),
572 m_size (size),
573 m_result (result)
574 {
575 }
576
577 void Execute (NativeProcessLinux *process) override;
578
579 private:
580 lldb::addr_t m_addr;
581 const void *m_buff;
582 lldb::addr_t m_size;
583 lldb::addr_t &m_result;
584 };
585
586 void
587 WriteOperation::Execute(NativeProcessLinux *process)
588 {
589 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
590 }
591
592 //------------------------------------------------------------------------------
593 /// @class ReadRegOperation
594 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
595 class ReadRegOperation : public Operation
596 {
597 public:
598 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000599 RegisterValue &value)
600 : m_tid(tid),
601 m_offset(static_cast<uintptr_t> (offset)),
602 m_reg_name(reg_name),
603 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000604 { }
605
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000606 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000607
608 private:
609 lldb::tid_t m_tid;
610 uintptr_t m_offset;
611 const char *m_reg_name;
612 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000613 };
614
615 void
616 ReadRegOperation::Execute(NativeProcessLinux *monitor)
617 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000618#if defined (__arm64__) || defined (__aarch64__)
619 if (m_offset > sizeof(struct user_pt_regs))
620 {
621 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
622 if (offset > sizeof(struct user_fpsimd_state))
623 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000624 m_error.SetErrorString("invalid offset value");
625 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000626 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000627 elf_fpregset_t regs;
628 int regset = NT_FPREGSET;
629 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000630
Chaoren Lin97ccc292015-02-03 01:51:12 +0000631 ioVec.iov_base = &regs;
632 ioVec.iov_len = sizeof regs;
633 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
634 if (m_error.Success())
635 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000636 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000637 if (monitor->GetArchitecture(arch))
638 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000639 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000640 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000641 }
642 }
643 else
644 {
645 elf_gregset_t regs;
646 int regset = NT_PRSTATUS;
647 struct iovec ioVec;
648
649 ioVec.iov_base = &regs;
650 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000651 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
652 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000653 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000654 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000656 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000657 else
658 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000659 }
660 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000661#elif defined (__mips__)
662 elf_gregset_t regs;
663 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
664 if (m_error.Success())
665 {
666 lldb_private::ArchSpec arch;
667 if (monitor->GetArchitecture(arch))
668 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
669 else
670 m_error.SetErrorString("failed to get architecture");
671 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000672#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000673 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
674
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000675 lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error));
Chaoren Lin97ccc292015-02-03 01:51:12 +0000676 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000677 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000678
Todd Fialaaf245d12014-06-30 21:05:18 +0000679 if (log)
680 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
681 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000682#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000683 }
684
685 //------------------------------------------------------------------------------
686 /// @class WriteRegOperation
687 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
688 class WriteRegOperation : public Operation
689 {
690 public:
691 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000692 const RegisterValue &value)
693 : m_tid(tid),
694 m_offset(offset),
695 m_reg_name(reg_name),
696 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000697 { }
698
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000699 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000700
701 private:
702 lldb::tid_t m_tid;
703 uintptr_t m_offset;
704 const char *m_reg_name;
705 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000706 };
707
708 void
709 WriteRegOperation::Execute(NativeProcessLinux *monitor)
710 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000711#if defined (__arm64__) || defined (__aarch64__)
712 if (m_offset > sizeof(struct user_pt_regs))
713 {
714 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
715 if (offset > sizeof(struct user_fpsimd_state))
716 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000717 m_error.SetErrorString("invalid offset value");
718 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000719 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000720 elf_fpregset_t regs;
721 int regset = NT_FPREGSET;
722 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000723
Chaoren Lin97ccc292015-02-03 01:51:12 +0000724 ioVec.iov_base = &regs;
725 ioVec.iov_len = sizeof regs;
726 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000727 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000728 {
729 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
730 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000731 }
732 }
733 else
734 {
735 elf_gregset_t regs;
736 int regset = NT_PRSTATUS;
737 struct iovec ioVec;
738
739 ioVec.iov_base = &regs;
740 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000741 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000742 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000743 {
744 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000745 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000746 }
747 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000748#elif defined (__mips__)
749 elf_gregset_t regs;
750 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
751 if (m_error.Success())
752 {
753 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
754 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
755 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000756#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000757 void* buf;
758 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
759
760 buf = (void*) m_value.GetAsUInt64();
761
762 if (log)
763 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000764 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000765#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000766 }
767
768 //------------------------------------------------------------------------------
769 /// @class ReadGPROperation
770 /// @brief Implements NativeProcessLinux::ReadGPR.
771 class ReadGPROperation : public Operation
772 {
773 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000774 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
775 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000776 { }
777
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000778 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000779
780 private:
781 lldb::tid_t m_tid;
782 void *m_buf;
783 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000784 };
785
786 void
787 ReadGPROperation::Execute(NativeProcessLinux *monitor)
788 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000789#if defined (__arm64__) || defined (__aarch64__)
790 int regset = NT_PRSTATUS;
791 struct iovec ioVec;
792
793 ioVec.iov_base = m_buf;
794 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000795 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000796#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000797 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000798#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000799 }
800
801 //------------------------------------------------------------------------------
802 /// @class ReadFPROperation
803 /// @brief Implements NativeProcessLinux::ReadFPR.
804 class ReadFPROperation : public Operation
805 {
806 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000807 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
808 : m_tid(tid),
809 m_buf(buf),
810 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000811 { }
812
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000813 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000814
815 private:
816 lldb::tid_t m_tid;
817 void *m_buf;
818 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000819 };
820
821 void
822 ReadFPROperation::Execute(NativeProcessLinux *monitor)
823 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000824#if defined (__arm64__) || defined (__aarch64__)
825 int regset = NT_FPREGSET;
826 struct iovec ioVec;
827
828 ioVec.iov_base = m_buf;
829 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000830 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000831#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000832 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000833#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000834 }
835
836 //------------------------------------------------------------------------------
837 /// @class ReadRegisterSetOperation
838 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
839 class ReadRegisterSetOperation : public Operation
840 {
841 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000842 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
843 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000844 { }
845
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000846 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000847
848 private:
849 lldb::tid_t m_tid;
850 void *m_buf;
851 size_t m_buf_size;
852 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000853 };
854
855 void
856 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
857 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000858 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000859 }
860
861 //------------------------------------------------------------------------------
862 /// @class WriteGPROperation
863 /// @brief Implements NativeProcessLinux::WriteGPR.
864 class WriteGPROperation : public Operation
865 {
866 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000867 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
868 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000869 { }
870
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000871 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000872
873 private:
874 lldb::tid_t m_tid;
875 void *m_buf;
876 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000877 };
878
879 void
880 WriteGPROperation::Execute(NativeProcessLinux *monitor)
881 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000882#if defined (__arm64__) || defined (__aarch64__)
883 int regset = NT_PRSTATUS;
884 struct iovec ioVec;
885
886 ioVec.iov_base = m_buf;
887 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000888 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000889#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000890 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000891#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000892 }
893
894 //------------------------------------------------------------------------------
895 /// @class WriteFPROperation
896 /// @brief Implements NativeProcessLinux::WriteFPR.
897 class WriteFPROperation : public Operation
898 {
899 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000900 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
901 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000902 { }
903
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000904 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000905
906 private:
907 lldb::tid_t m_tid;
908 void *m_buf;
909 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000910 };
911
912 void
913 WriteFPROperation::Execute(NativeProcessLinux *monitor)
914 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000915#if defined (__arm64__) || defined (__aarch64__)
916 int regset = NT_FPREGSET;
917 struct iovec ioVec;
918
919 ioVec.iov_base = m_buf;
920 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000921 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000922#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000923 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000924#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000925 }
926
927 //------------------------------------------------------------------------------
928 /// @class WriteRegisterSetOperation
929 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
930 class WriteRegisterSetOperation : public Operation
931 {
932 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000933 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
934 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000935 { }
936
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000937 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000938
939 private:
940 lldb::tid_t m_tid;
941 void *m_buf;
942 size_t m_buf_size;
943 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000944 };
945
946 void
947 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
948 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000949 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000950 }
951
952 //------------------------------------------------------------------------------
953 /// @class ResumeOperation
954 /// @brief Implements NativeProcessLinux::Resume.
955 class ResumeOperation : public Operation
956 {
957 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000958 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
959 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000960
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000961 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000962
963 private:
964 lldb::tid_t m_tid;
965 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000966 };
967
968 void
969 ResumeOperation::Execute(NativeProcessLinux *monitor)
970 {
971 intptr_t data = 0;
972
973 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
974 data = m_signo;
975
Chaoren Lin97ccc292015-02-03 01:51:12 +0000976 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
977 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000978 {
979 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
980
981 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000982 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000983 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000984 }
985
986 //------------------------------------------------------------------------------
987 /// @class SingleStepOperation
988 /// @brief Implements NativeProcessLinux::SingleStep.
989 class SingleStepOperation : public Operation
990 {
991 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000992 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
993 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000994
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000995 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000996
997 private:
998 lldb::tid_t m_tid;
999 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +00001000 };
1001
1002 void
1003 SingleStepOperation::Execute(NativeProcessLinux *monitor)
1004 {
1005 intptr_t data = 0;
1006
1007 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1008 data = m_signo;
1009
Chaoren Lin97ccc292015-02-03 01:51:12 +00001010 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001011 }
1012
1013 //------------------------------------------------------------------------------
1014 /// @class SiginfoOperation
1015 /// @brief Implements NativeProcessLinux::GetSignalInfo.
1016 class SiginfoOperation : public Operation
1017 {
1018 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001019 SiginfoOperation(lldb::tid_t tid, void *info)
1020 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001021
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001022 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001023
1024 private:
1025 lldb::tid_t m_tid;
1026 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001027 };
1028
1029 void
1030 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1031 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001032 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001033 }
1034
1035 //------------------------------------------------------------------------------
1036 /// @class EventMessageOperation
1037 /// @brief Implements NativeProcessLinux::GetEventMessage.
1038 class EventMessageOperation : public Operation
1039 {
1040 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001041 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1042 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001044 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001045
1046 private:
1047 lldb::tid_t m_tid;
1048 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001049 };
1050
1051 void
1052 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1053 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001054 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001055 }
1056
1057 class DetachOperation : public Operation
1058 {
1059 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001060 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001061
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001062 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001063
1064 private:
1065 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001066 };
1067
1068 void
1069 DetachOperation::Execute(NativeProcessLinux *monitor)
1070 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001071 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001072 }
1073
1074}
1075
Todd Fialaaf245d12014-06-30 21:05:18 +00001076// Simple helper function to ensure flags are enabled on the given file
1077// descriptor.
1078static bool
1079EnsureFDFlags(int fd, int flags, Error &error)
1080{
1081 int status;
1082
1083 if ((status = fcntl(fd, F_GETFL)) == -1)
1084 {
1085 error.SetErrorToErrno();
1086 return false;
1087 }
1088
1089 if (fcntl(fd, F_SETFL, status | flags) == -1)
1090 {
1091 error.SetErrorToErrno();
1092 return false;
1093 }
1094
1095 return true;
1096}
1097
1098NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1099 : m_monitor(monitor)
1100{
1101 sem_init(&m_semaphore, 0, 0);
1102}
1103
1104NativeProcessLinux::OperationArgs::~OperationArgs()
1105{
1106 sem_destroy(&m_semaphore);
1107}
1108
1109NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001110 Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001111 char const **argv,
1112 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001113 const std::string &stdin_path,
1114 const std::string &stdout_path,
1115 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001116 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001117 const ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001118 : OperationArgs(monitor),
1119 m_module(module),
1120 m_argv(argv),
1121 m_envp(envp),
1122 m_stdin_path(stdin_path),
1123 m_stdout_path(stdout_path),
1124 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001125 m_working_dir(working_dir),
1126 m_launch_info(launch_info)
1127{
1128}
Todd Fialaaf245d12014-06-30 21:05:18 +00001129
1130NativeProcessLinux::LaunchArgs::~LaunchArgs()
1131{ }
1132
1133NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1134 lldb::pid_t pid)
1135 : OperationArgs(monitor), m_pid(pid) { }
1136
1137NativeProcessLinux::AttachArgs::~AttachArgs()
1138{ }
1139
1140// -----------------------------------------------------------------------------
1141// Public Static Methods
1142// -----------------------------------------------------------------------------
1143
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001144Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001145NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001146 Module *exe_module,
1147 ProcessLaunchInfo &launch_info,
1148 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001149 NativeProcessProtocolSP &native_process_sp)
1150{
1151 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1152
1153 Error error;
1154
1155 // Verify the working directory is valid if one was specified.
1156 const char* working_dir = launch_info.GetWorkingDirectory ();
1157 if (working_dir)
1158 {
1159 FileSpec working_dir_fs (working_dir, true);
1160 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1161 {
1162 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1163 return error;
1164 }
1165 }
1166
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001167 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001168
1169 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001170 std::string stdin_path;
1171 std::string stdout_path;
1172 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001173
1174 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001175 if (file_action)
1176 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001177
1178 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001179 if (file_action)
1180 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001181
1182 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001183 if (file_action)
1184 stderr_path = file_action->GetPath ();
1185
1186 if (log)
1187 {
1188 if (!stdin_path.empty ())
1189 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1190 else
1191 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1192
1193 if (!stdout_path.empty ())
1194 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1195 else
1196 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1197
1198 if (!stderr_path.empty ())
1199 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1200 else
1201 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1202 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001203
1204 // Create the NativeProcessLinux in launch mode.
1205 native_process_sp.reset (new NativeProcessLinux ());
1206
1207 if (log)
1208 {
1209 int i = 0;
1210 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1211 {
1212 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1213 ++i;
1214 }
1215 }
1216
1217 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1218 {
1219 native_process_sp.reset ();
1220 error.SetErrorStringWithFormat ("failed to register the native delegate");
1221 return error;
1222 }
1223
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001224 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001225 exe_module,
1226 launch_info.GetArguments ().GetConstArgumentVector (),
1227 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1228 stdin_path,
1229 stdout_path,
1230 stderr_path,
1231 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001232 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001233 error);
1234
1235 if (error.Fail ())
1236 {
1237 native_process_sp.reset ();
1238 if (log)
1239 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1240 return error;
1241 }
1242
1243 launch_info.SetProcessID (native_process_sp->GetID ());
1244
1245 return error;
1246}
1247
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001248Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001249NativeProcessLinux::AttachToProcess (
1250 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001251 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001252 NativeProcessProtocolSP &native_process_sp)
1253{
1254 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1255 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1256 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1257
1258 // Grab the current platform architecture. This should be Linux,
1259 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001260 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001261 if (!platform_sp)
1262 return Error("failed to get a valid default platform");
1263
1264 // Retrieve the architecture for the running process.
1265 ArchSpec process_arch;
1266 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1267 if (!error.Success ())
1268 return error;
1269
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001270 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001271
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001272 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001273 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001274 error.SetErrorStringWithFormat ("failed to register the native delegate");
1275 return error;
1276 }
1277
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001278 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001279 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001280 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001281
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001282 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001283 return error;
1284}
1285
1286// -----------------------------------------------------------------------------
1287// Public Instance Methods
1288// -----------------------------------------------------------------------------
1289
1290NativeProcessLinux::NativeProcessLinux () :
1291 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1292 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001293 m_operation_thread (),
1294 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001295 m_operation (nullptr),
1296 m_operation_mutex (),
1297 m_operation_pending (),
1298 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001299 m_supports_mem_region (eLazyBoolCalculate),
1300 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001301 m_mem_region_cache_mutex (),
1302 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1303 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001304{
1305}
1306
1307//------------------------------------------------------------------------------
1308/// The basic design of the NativeProcessLinux is built around two threads.
1309///
1310/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1311/// for changes in the debugee state. When a change is detected a
1312/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1313/// "drives" state changes in the debugger.
1314///
1315/// The second thread (@see OperationThread) is responsible for two things 1)
1316/// launching or attaching to the inferior process, and then 2) servicing
1317/// operations such as register reads/writes, stepping, etc. See the comments
1318/// on the Operation class for more info as to why this is needed.
1319void
1320NativeProcessLinux::LaunchInferior (
1321 Module *module,
1322 const char *argv[],
1323 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001324 const std::string &stdin_path,
1325 const std::string &stdout_path,
1326 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001327 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001328 const ProcessLaunchInfo &launch_info,
1329 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001330{
1331 if (module)
1332 m_arch = module->GetArchitecture ();
1333
Chaoren Linfa03ad22015-02-03 01:50:42 +00001334 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001335
1336 std::unique_ptr<LaunchArgs> args(
1337 new LaunchArgs(
1338 this, module, argv, envp,
1339 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001340 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001341
Chaoren Linfa03ad22015-02-03 01:50:42 +00001342 sem_init (&m_operation_pending, 0, 0);
1343 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001344
Chaoren Linfa03ad22015-02-03 01:50:42 +00001345 StartLaunchOpThread (args.get(), error);
1346 if (!error.Success ())
1347 return;
1348
1349 error = StartCoordinatorThread ();
1350 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001351 return;
1352
1353WAIT_AGAIN:
1354 // Wait for the operation thread to initialize.
1355 if (sem_wait(&args->m_semaphore))
1356 {
1357 if (errno == EINTR)
1358 goto WAIT_AGAIN;
1359 else
1360 {
1361 error.SetErrorToErrno();
1362 return;
1363 }
1364 }
1365
1366 // Check that the launch was a success.
1367 if (!args->m_error.Success())
1368 {
1369 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001370 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001371 error = args->m_error;
1372 return;
1373 }
1374
1375 // Finally, start monitoring the child process for change in state.
1376 m_monitor_thread = Host::StartMonitoringChildProcess(
1377 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001378 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001379 {
1380 error.SetErrorToGenericError();
1381 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1382 return;
1383 }
1384}
1385
1386void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001387NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001388{
1389 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1390 if (log)
1391 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1392
1393 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001394 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001395 if (!platform_sp)
1396 {
1397 if (log)
1398 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1399 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001400 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001401 }
1402
1403 // Gather info about the process.
1404 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001405 if (!platform_sp->GetProcessInfo (pid, process_info))
1406 {
1407 if (log)
1408 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1409 error.SetErrorString ("failed to get process info");
1410 return;
1411 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001412
1413 // Resolve the executable module
1414 ModuleSP exe_module_sp;
1415 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001416 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001417 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001418 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001419 if (!error.Success())
1420 return;
1421
1422 // Set the architecture to the exe architecture.
1423 m_arch = exe_module_sp->GetArchitecture();
1424 if (log)
1425 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1426
1427 m_pid = pid;
1428 SetState(eStateAttaching);
1429
1430 sem_init (&m_operation_pending, 0, 0);
1431 sem_init (&m_operation_done, 0, 0);
1432
1433 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1434
1435 StartAttachOpThread(args.get (), error);
1436 if (!error.Success ())
1437 return;
1438
Chaoren Linfa03ad22015-02-03 01:50:42 +00001439 error = StartCoordinatorThread ();
1440 if (!error.Success ())
1441 return;
1442
Todd Fialaaf245d12014-06-30 21:05:18 +00001443WAIT_AGAIN:
1444 // Wait for the operation thread to initialize.
1445 if (sem_wait (&args->m_semaphore))
1446 {
1447 if (errno == EINTR)
1448 goto WAIT_AGAIN;
1449 else
1450 {
1451 error.SetErrorToErrno ();
1452 return;
1453 }
1454 }
1455
1456 // Check that the attach was a success.
1457 if (!args->m_error.Success ())
1458 {
1459 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001460 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001461 error = args->m_error;
1462 return;
1463 }
1464
1465 // Finally, start monitoring the child process for change in state.
1466 m_monitor_thread = Host::StartMonitoringChildProcess (
1467 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001468 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001469 {
1470 error.SetErrorToGenericError ();
1471 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1472 return;
1473 }
1474}
1475
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001476void
1477NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001478{
1479 StopMonitor();
1480}
1481
1482//------------------------------------------------------------------------------
1483// Thread setup and tear down.
1484
1485void
1486NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1487{
1488 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1489
Zachary Turneracee96a2014-09-23 18:32:09 +00001490 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001491 return;
1492
Zachary Turner39de3112014-09-09 20:54:56 +00001493 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001494}
1495
1496void *
1497NativeProcessLinux::LaunchOpThread(void *arg)
1498{
1499 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1500
1501 if (!Launch(args)) {
1502 sem_post(&args->m_semaphore);
1503 return NULL;
1504 }
1505
1506 ServeOperation(args);
1507 return NULL;
1508}
1509
1510bool
1511NativeProcessLinux::Launch(LaunchArgs *args)
1512{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001513 assert (args && "null args");
1514 if (!args)
1515 return false;
1516
Todd Fialaaf245d12014-06-30 21:05:18 +00001517 NativeProcessLinux *monitor = args->m_monitor;
1518 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001519
1520 const char **argv = args->m_argv;
1521 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001522 const char *working_dir = args->m_working_dir;
1523
1524 lldb_utility::PseudoTerminal terminal;
1525 const size_t err_len = 1024;
1526 char err_str[err_len];
1527 lldb::pid_t pid;
1528 NativeThreadProtocolSP thread_sp;
1529
1530 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001531
1532 // Propagate the environment if one is not supplied.
1533 if (envp == NULL || envp[0] == NULL)
1534 envp = const_cast<const char **>(environ);
1535
1536 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1537 {
1538 args->m_error.SetErrorToGenericError();
1539 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001540 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001541 }
1542
1543 // Recognized child exit status codes.
1544 enum {
1545 ePtraceFailed = 1,
1546 eDupStdinFailed,
1547 eDupStdoutFailed,
1548 eDupStderrFailed,
1549 eChdirFailed,
1550 eExecFailed,
1551 eSetGidFailed
1552 };
1553
1554 // Child process.
1555 if (pid == 0)
1556 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001557 // FIXME consider opening a pipe between parent/child and have this forked child
1558 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001559
Todd Fiala75f47c32014-10-11 21:42:09 +00001560 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001561 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1562 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001563 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001564
Pavel Labath493c3a12015-02-04 10:36:57 +00001565 // terminal has already dupped the tty descriptors to stdin/out/err.
1566 // This closes original fd from which they were copied (and avoids
1567 // leaking descriptors to the debugged process.
1568 terminal.CloseSlaveFileDescriptor();
1569
Todd Fialaaf245d12014-06-30 21:05:18 +00001570 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001572 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001573
1574 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001575 if (setpgid(0, 0) != 0)
1576 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001577 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001578 // Don't allow this to prevent an inferior exec.
1579 }
1580
1581 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001582 if (!args->m_stdin_path.empty ())
1583 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001584 exit(eDupStdinFailed);
1585
Todd Fiala75f47c32014-10-11 21:42:09 +00001586 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001587 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001588 exit(eDupStdoutFailed);
1589
Todd Fiala75f47c32014-10-11 21:42:09 +00001590 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001591 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001592 exit(eDupStderrFailed);
1593
1594 // Change working directory
1595 if (working_dir != NULL && working_dir[0])
1596 if (0 != ::chdir(working_dir))
1597 exit(eChdirFailed);
1598
Todd Fiala0bce1b62014-08-17 00:10:50 +00001599 // Disable ASLR if requested.
1600 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1601 {
1602 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1603 if (old_personality == -1)
1604 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001605 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001606 }
1607 else
1608 {
1609 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1610 if (new_personality == -1)
1611 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001612 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001613 }
1614 else
1615 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001616 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001617 }
1618 }
1619 }
1620
Todd Fiala75f47c32014-10-11 21:42:09 +00001621 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001622 execve(argv[0],
1623 const_cast<char *const *>(argv),
1624 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001625
1626 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001627 exit(eExecFailed);
1628 }
1629
Todd Fiala75f47c32014-10-11 21:42:09 +00001630 //
1631 // This is the parent code here.
1632 //
1633 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1634
Todd Fialaaf245d12014-06-30 21:05:18 +00001635 // Wait for the child process to trap on its call to execve.
1636 ::pid_t wpid;
1637 int status;
1638 if ((wpid = waitpid(pid, &status, 0)) < 0)
1639 {
1640 args->m_error.SetErrorToErrno();
1641
1642 if (log)
1643 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1644
1645 // Mark the inferior as invalid.
1646 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1647 monitor->SetState (StateType::eStateInvalid);
1648
Todd Fiala75f47c32014-10-11 21:42:09 +00001649 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001650 }
1651 else if (WIFEXITED(status))
1652 {
1653 // open, dup or execve likely failed for some reason.
1654 args->m_error.SetErrorToGenericError();
1655 switch (WEXITSTATUS(status))
1656 {
1657 case ePtraceFailed:
1658 args->m_error.SetErrorString("Child ptrace failed.");
1659 break;
1660 case eDupStdinFailed:
1661 args->m_error.SetErrorString("Child open stdin failed.");
1662 break;
1663 case eDupStdoutFailed:
1664 args->m_error.SetErrorString("Child open stdout failed.");
1665 break;
1666 case eDupStderrFailed:
1667 args->m_error.SetErrorString("Child open stderr failed.");
1668 break;
1669 case eChdirFailed:
1670 args->m_error.SetErrorString("Child failed to set working directory.");
1671 break;
1672 case eExecFailed:
1673 args->m_error.SetErrorString("Child exec failed.");
1674 break;
1675 case eSetGidFailed:
1676 args->m_error.SetErrorString("Child setgid failed.");
1677 break;
1678 default:
1679 args->m_error.SetErrorString("Child returned unknown exit status.");
1680 break;
1681 }
1682
1683 if (log)
1684 {
1685 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1686 __FUNCTION__,
1687 WEXITSTATUS(status));
1688 }
1689
1690 // Mark the inferior as invalid.
1691 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1692 monitor->SetState (StateType::eStateInvalid);
1693
Todd Fiala75f47c32014-10-11 21:42:09 +00001694 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001695 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001696 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001697 "Could not sync with inferior process.");
1698
1699 if (log)
1700 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1701
Chaoren Lin97ccc292015-02-03 01:51:12 +00001702 args->m_error = SetDefaultPtraceOpts(pid);
1703 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001704 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001705 if (log)
1706 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %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 // Release the master terminal descriptor and pass it off to the
1718 // NativeProcessLinux instance. Similarly stash the inferior pid.
1719 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1720 monitor->m_pid = pid;
1721
1722 // Set the terminal fd to be in non blocking mode (it simplifies the
1723 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1724 // descriptor to read from).
1725 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1726 {
1727 if (log)
1728 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1729 __FUNCTION__,
1730 args->m_error.AsCString ());
1731
1732 // Mark the inferior as invalid.
1733 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1734 monitor->SetState (StateType::eStateInvalid);
1735
Todd Fiala75f47c32014-10-11 21:42:09 +00001736 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 }
1738
1739 if (log)
1740 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1741
Chaoren Linfa03ad22015-02-03 01:50:42 +00001742 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001743 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001744 monitor->NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001745 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001746
1747 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001748 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001749 monitor->SetState (StateType::eStateStopped);
1750
Todd Fialaaf245d12014-06-30 21:05:18 +00001751 if (log)
1752 {
1753 if (args->m_error.Success ())
1754 {
1755 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1756 }
1757 else
1758 {
1759 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1760 __FUNCTION__,
1761 args->m_error.AsCString ());
1762 }
1763 }
1764 return args->m_error.Success();
1765}
1766
1767void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001768NativeProcessLinux::StartAttachOpThread(AttachArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001769{
1770 static const char *g_thread_name = "lldb.process.linux.operation";
1771
Zachary Turneracee96a2014-09-23 18:32:09 +00001772 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001773 return;
1774
Zachary Turner39de3112014-09-09 20:54:56 +00001775 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001776}
1777
1778void *
1779NativeProcessLinux::AttachOpThread(void *arg)
1780{
1781 AttachArgs *args = static_cast<AttachArgs*>(arg);
1782
1783 if (!Attach(args)) {
1784 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001785 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001786 }
1787
1788 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001789 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001790}
1791
1792bool
1793NativeProcessLinux::Attach(AttachArgs *args)
1794{
1795 lldb::pid_t pid = args->m_pid;
1796
1797 NativeProcessLinux *monitor = args->m_monitor;
1798 lldb::ThreadSP inferior;
1799 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1800
1801 // Use a map to keep track of the threads which we have attached/need to attach.
1802 Host::TidMap tids_to_attach;
1803 if (pid <= 1)
1804 {
1805 args->m_error.SetErrorToGenericError();
1806 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1807 goto FINISH;
1808 }
1809
1810 while (Host::FindProcessThreads(pid, tids_to_attach))
1811 {
1812 for (Host::TidMap::iterator it = tids_to_attach.begin();
1813 it != tids_to_attach.end();)
1814 {
1815 if (it->second == false)
1816 {
1817 lldb::tid_t tid = it->first;
1818
1819 // Attach to the requested process.
1820 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001821 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1822 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001823 {
1824 // No such thread. The thread may have exited.
1825 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001826 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001827 {
1828 it = tids_to_attach.erase(it);
1829 continue;
1830 }
1831 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001832 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001833 }
1834
1835 int status;
1836 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1837 // At this point we should have a thread stopped if waitpid succeeds.
1838 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1839 {
1840 // No such thread. The thread may have exited.
1841 // More error handling may be needed.
1842 if (errno == ESRCH)
1843 {
1844 it = tids_to_attach.erase(it);
1845 continue;
1846 }
1847 else
1848 {
1849 args->m_error.SetErrorToErrno();
1850 goto FINISH;
1851 }
1852 }
1853
Chaoren Lin97ccc292015-02-03 01:51:12 +00001854 args->m_error = SetDefaultPtraceOpts(tid);
1855 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001856 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001857
1858
1859 if (log)
1860 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1861
1862 it->second = true;
1863
1864 // Create the thread, mark it as stopped.
1865 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1866 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001867
1868 // This will notify this is a new thread and tell the system it is stopped.
1869 monitor->NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001870 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001871 monitor->SetCurrentThreadID (thread_sp->GetID ());
1872 }
1873
1874 // move the loop forward
1875 ++it;
1876 }
1877 }
1878
1879 if (tids_to_attach.size() > 0)
1880 {
1881 monitor->m_pid = pid;
1882 // Let our process instance know the thread has stopped.
1883 monitor->SetState (StateType::eStateStopped);
1884 }
1885 else
1886 {
1887 args->m_error.SetErrorToGenericError();
1888 args->m_error.SetErrorString("No such process.");
1889 }
1890
1891 FINISH:
1892 return args->m_error.Success();
1893}
1894
Chaoren Lin97ccc292015-02-03 01:51:12 +00001895Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001896NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1897{
1898 long ptrace_opts = 0;
1899
1900 // Have the child raise an event on exit. This is used to keep the child in
1901 // limbo until it is destroyed.
1902 ptrace_opts |= PTRACE_O_TRACEEXIT;
1903
1904 // Have the tracer trace threads which spawn in the inferior process.
1905 // TODO: if we want to support tracing the inferiors' child, add the
1906 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1907 ptrace_opts |= PTRACE_O_TRACECLONE;
1908
1909 // Have the tracer notify us before execve returns
1910 // (needed to disable legacy SIGTRAP generation)
1911 ptrace_opts |= PTRACE_O_TRACEEXEC;
1912
Chaoren Lin97ccc292015-02-03 01:51:12 +00001913 Error error;
1914 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1915 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001916}
1917
1918static ExitType convert_pid_status_to_exit_type (int status)
1919{
1920 if (WIFEXITED (status))
1921 return ExitType::eExitTypeExit;
1922 else if (WIFSIGNALED (status))
1923 return ExitType::eExitTypeSignal;
1924 else if (WIFSTOPPED (status))
1925 return ExitType::eExitTypeStop;
1926 else
1927 {
1928 // We don't know what this is.
1929 return ExitType::eExitTypeInvalid;
1930 }
1931}
1932
1933static int convert_pid_status_to_return_code (int status)
1934{
1935 if (WIFEXITED (status))
1936 return WEXITSTATUS (status);
1937 else if (WIFSIGNALED (status))
1938 return WTERMSIG (status);
1939 else if (WIFSTOPPED (status))
1940 return WSTOPSIG (status);
1941 else
1942 {
1943 // We don't know what this is.
1944 return ExitType::eExitTypeInvalid;
1945 }
1946}
1947
1948// Main process monitoring waitpid-loop handler.
1949bool
1950NativeProcessLinux::MonitorCallback(void *callback_baton,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001951 lldb::pid_t pid,
1952 bool exited,
1953 int signal,
1954 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001955{
1956 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1957
1958 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1959 assert (process && "process is null");
1960 if (!process)
1961 {
1962 if (log)
1963 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1964 return true;
1965 }
1966
1967 // Certain activities differ based on whether the pid is the tid of the main thread.
1968 const bool is_main_thread = (pid == process->GetID ());
1969
1970 // Assume we keep monitoring by default.
1971 bool stop_monitoring = false;
1972
1973 // Handle when the thread exits.
1974 if (exited)
1975 {
1976 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001977 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 +00001978
1979 // This is a thread that exited. Ensure we're not tracking it anymore.
1980 const bool thread_found = process->StopTrackingThread (pid);
1981
Chaoren Linfa03ad22015-02-03 01:50:42 +00001982 // Make sure the thread state coordinator knows about this.
1983 process->NotifyThreadDeath (pid);
1984
Todd Fialaaf245d12014-06-30 21:05:18 +00001985 if (is_main_thread)
1986 {
1987 // We only set the exit status and notify the delegate if we haven't already set the process
1988 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1989 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001990 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001991 if (!already_notified)
1992 {
1993 if (log)
1994 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 ()));
1995 // The main thread exited. We're done monitoring. Report to delegate.
1996 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1997
1998 // Notify delegate that our process has exited.
1999 process->SetState (StateType::eStateExited, true);
2000 }
2001 else
2002 {
2003 if (log)
2004 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2005 }
2006 return true;
2007 }
2008 else
2009 {
2010 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2011 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2012 // and we would have done an all-stop then.
2013 if (log)
2014 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2015
2016 // Not the main thread, we keep going.
2017 return false;
2018 }
2019 }
2020
2021 // Get details on the signal raised.
2022 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002023 const auto err = process->GetSignalInfo(pid, &info);
2024 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002025 {
2026 // We have retrieved the signal info. Dispatch appropriately.
2027 if (info.si_signo == SIGTRAP)
2028 process->MonitorSIGTRAP(&info, pid);
2029 else
2030 process->MonitorSignal(&info, pid, exited);
2031
2032 stop_monitoring = false;
2033 }
2034 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002035 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002036 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002037 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002038 // This is a group stop reception for this tid.
2039 if (log)
2040 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2041 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002042 }
2043 else
2044 {
2045 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2046
2047 // A return value of ESRCH means the thread/process is no longer on the system,
2048 // so it was killed somehow outside of our control. Either way, we can't do anything
2049 // with it anymore.
2050
2051 // We stop monitoring if it was the main thread.
2052 stop_monitoring = is_main_thread;
2053
2054 // Stop tracking the metadata for the thread since it's entirely off the system now.
2055 const bool thread_found = process->StopTrackingThread (pid);
2056
Chaoren Linfa03ad22015-02-03 01:50:42 +00002057 // Make sure the thread state coordinator knows about this.
2058 process->NotifyThreadDeath (pid);
2059
Todd Fialaaf245d12014-06-30 21:05:18 +00002060 if (log)
2061 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002062 __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 +00002063
2064 if (is_main_thread)
2065 {
2066 // Notify the delegate - our process is not available but appears to have been killed outside
2067 // our control. Is eStateExited the right exit state in this case?
2068 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2069 process->SetState (StateType::eStateExited, true);
2070 }
2071 else
2072 {
2073 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2074 if (log)
2075 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);
2076 }
2077 }
2078 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002079
2080 return stop_monitoring;
2081}
2082
2083void
2084NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2085{
2086 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2087 const bool is_main_thread = (pid == GetID ());
2088
2089 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2090 if (!info)
2091 return;
2092
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002093 Mutex::Locker locker (m_threads_mutex);
2094
Todd Fialaaf245d12014-06-30 21:05:18 +00002095 // See if we can find a thread for this signal.
2096 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2097 if (!thread_sp)
2098 {
2099 if (log)
2100 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2101 }
2102
2103 switch (info->si_code)
2104 {
2105 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2106 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2107 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2108
2109 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2110 {
2111 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2112
Chaoren Linfa03ad22015-02-03 01:50:42 +00002113 // The main thread is stopped here.
2114 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002115 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002116 NotifyThreadStop (pid);
2117
Todd Fialaaf245d12014-06-30 21:05:18 +00002118 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002119 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002120 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002121 tid = static_cast<lldb::tid_t> (event_message);
2122 if (log)
2123 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002124
Chaoren Linfa03ad22015-02-03 01:50:42 +00002125 // If we don't track the thread yet: create it, mark as stopped.
2126 // If we do track it, this is the wait we needed. Now resume the new thread.
2127 // In all cases, resume the current (i.e. main process) thread.
2128 bool created_now = false;
2129 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2130 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2131
2132 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2133 if (!created_now)
2134 {
2135 // We can now resume the newly created thread since it is fully created.
2136 NotifyThreadCreateStopped (tid);
2137 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002138 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002139 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002140 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002141 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002142 },
2143 CoordinatorErrorHandler);
2144 }
2145 else
2146 {
2147 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2148 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002149 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetLaunching ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002150 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002151 }
2152 else
2153 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002154 if (log)
2155 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 +00002156 }
2157
2158 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002159 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002160 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002161 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002162 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002163 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002164 },
2165 CoordinatorErrorHandler);
2166
Todd Fialaaf245d12014-06-30 21:05:18 +00002167 break;
2168 }
2169
2170 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002171 {
2172 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002173 if (log)
2174 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002175
Chaoren Linfa03ad22015-02-03 01:50:42 +00002176 // The thread state coordinator needs to reset due to the exec.
2177 m_coordinator_up->ResetForExec ();
2178
2179 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002180 if (log)
2181 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2182
2183 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002184 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002185 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2186 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002187 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002188 main_thread_sp = thread_sp;
2189 if (log)
2190 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002191 }
2192 else
2193 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002194 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002195 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002196 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002197 }
2198 }
2199
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002200 m_threads.clear ();
2201
2202 if (main_thread_sp)
2203 {
2204 m_threads.push_back (main_thread_sp);
2205 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002206 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002207 }
2208 else
2209 {
2210 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2211 if (log)
2212 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2213 }
2214
Chaoren Linfa03ad22015-02-03 01:50:42 +00002215 // Tell coordinator about about the "new" (since exec) stopped main thread.
2216 const lldb::tid_t main_thread_tid = GetID ();
2217 NotifyThreadCreateStopped (main_thread_tid);
2218
2219 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2220 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002221 // Let our delegate know we have just exec'd.
2222 NotifyDidExec ();
2223
2224 // If we have a main thread, indicate we are stopped.
2225 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002226
2227 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002228 CallAfterRunningThreadsStop (pid,
2229 [=] (lldb::tid_t signaling_tid)
2230 {
2231 SetState (StateType::eStateStopped, true);
2232 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002233
Todd Fialaaf245d12014-06-30 21:05:18 +00002234 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002235 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002236
2237 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2238 {
2239 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002240
2241 // This thread is currently stopped. It's not actually dead yet, just about to be.
2242 NotifyThreadStop (pid);
2243
Todd Fialaaf245d12014-06-30 21:05:18 +00002244 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002245 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002246 data = -1;
2247
2248 if (log)
2249 {
2250 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2251 __FUNCTION__,
2252 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2253 pid,
2254 is_main_thread ? "is main thread" : "not main thread");
2255 }
2256
Todd Fialaaf245d12014-06-30 21:05:18 +00002257 if (is_main_thread)
2258 {
2259 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002260 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002261
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002262 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002263 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002264 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002265 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002266 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002267 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002268 },
2269 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002270
2271 break;
2272 }
2273
2274 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002275 case TRAP_TRACE: // We receive this on single stepping.
2276 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002277 if (thread_sp)
2278 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002279 // If a watchpoint was hit, report it
2280 uint32_t wp_index;
2281 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2282 if (error.Fail() && log)
2283 log->Printf("NativeProcessLinux::%s() "
2284 "received error while checking for watchpoint hits, "
2285 "pid = %" PRIu64 " error = %s",
2286 __FUNCTION__, pid, error.AsCString());
2287 if (wp_index != LLDB_INVALID_INDEX32)
2288 {
2289 MonitorWatchpoint(pid, thread_sp, wp_index);
2290 break;
2291 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002292 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002293 // Otherwise, report step over
2294 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002295 break;
2296
2297 case SI_KERNEL:
2298 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002299 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002300 break;
2301
2302 case SIGTRAP:
2303 case (SIGTRAP | 0x80):
2304 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002305 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2306
2307 // This thread is currently stopped.
2308 NotifyThreadStop (pid);
2309 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002310 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002311
2312
Todd Fialaaf245d12014-06-30 21:05:18 +00002313 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002314 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002315 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002316 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002317 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002318 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002319 },
2320 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002321 break;
2322
2323 default:
2324 assert(false && "Unexpected SIGTRAP code!");
2325 if (log)
2326 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)));
2327 break;
2328
2329 }
2330}
2331
2332void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002333NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2334{
2335 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2336 if (log)
2337 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2338 __FUNCTION__, pid);
2339
2340 if (thread_sp)
2341 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2342
2343 // This thread is currently stopped.
2344 NotifyThreadStop(pid);
2345
2346 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2347 // This would have already happened at the time the Resume() with step operation was signaled.
2348 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2349 // once all running threads have checked in as stopped.
2350 SetCurrentThreadID(pid);
2351 // Tell the process we have a stop (from software breakpoint).
2352 CallAfterRunningThreadsStop(pid,
2353 [=](lldb::tid_t signaling_tid)
2354 {
2355 SetState(StateType::eStateStopped, true);
2356 });
2357}
2358
2359void
2360NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2361{
2362 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2363 if (log)
2364 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2365 __FUNCTION__, pid);
2366
2367 // This thread is currently stopped.
2368 NotifyThreadStop(pid);
2369
2370 // Mark the thread as stopped at breakpoint.
2371 if (thread_sp)
2372 {
2373 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2374 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2375 if (error.Fail())
2376 if (log)
2377 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2378 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002379
2380 auto it = m_threads_stepping_with_breakpoint.find(pid);
2381 if (it != m_threads_stepping_with_breakpoint.end())
2382 {
2383 Error error = RemoveBreakpoint (it->second);
2384 if (error.Fail())
2385 if (log)
2386 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2387 __FUNCTION__, pid, error.AsCString());
2388
2389 m_threads_stepping_with_breakpoint.erase(it);
2390 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2391 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002392 }
2393 else
2394 if (log)
2395 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2396 "warning, cannot process software breakpoint since no thread metadata",
2397 __FUNCTION__, pid);
2398
2399
2400 // We need to tell all other running threads before we notify the delegate about this stop.
2401 CallAfterRunningThreadsStop(pid,
2402 [=](lldb::tid_t deferred_notification_tid)
2403 {
2404 SetCurrentThreadID(deferred_notification_tid);
2405 // Tell the process we have a stop (from software breakpoint).
2406 SetState(StateType::eStateStopped, true);
2407 });
2408}
2409
2410void
2411NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2412{
2413 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2414 if (log)
2415 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2416 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2417 __FUNCTION__, pid, wp_index);
2418
2419 // This thread is currently stopped.
2420 NotifyThreadStop(pid);
2421
2422 // Mark the thread as stopped at watchpoint.
2423 // The address is at (lldb::addr_t)info->si_addr if we need it.
2424 lldbassert(thread_sp && "thread_sp cannot be NULL");
2425 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2426
2427 // We need to tell all other running threads before we notify the delegate about this stop.
2428 CallAfterRunningThreadsStop(pid,
2429 [=](lldb::tid_t deferred_notification_tid)
2430 {
2431 SetCurrentThreadID(deferred_notification_tid);
2432 // Tell the process we have a stop (from watchpoint).
2433 SetState(StateType::eStateStopped, true);
2434 });
2435}
2436
2437void
Todd Fialaaf245d12014-06-30 21:05:18 +00002438NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2439{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002440 assert (info && "null info");
2441 if (!info)
2442 return;
2443
2444 const int signo = info->si_signo;
2445 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002446
2447 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2448
2449 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2450 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2451 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2452 //
2453 // IOW, user generated signals never generate what we consider to be a
2454 // "crash".
2455 //
2456 // Similarly, ACK signals generated by this monitor.
2457
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002458 Mutex::Locker locker (m_threads_mutex);
2459
Todd Fialaaf245d12014-06-30 21:05:18 +00002460 // See if we can find a thread for this signal.
2461 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2462 if (!thread_sp)
2463 {
2464 if (log)
2465 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2466 }
2467
2468 // Handle the signal.
2469 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2470 {
2471 if (log)
2472 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2473 __FUNCTION__,
2474 GetUnixSignals ().GetSignalAsCString (signo),
2475 signo,
2476 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2477 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002478 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002479 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002480 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002481
Todd Fiala58a2f662014-08-12 17:02:07 +00002482 // Check for new thread notification.
2483 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2484 {
2485 // A new thread creation is being signaled. This is one of two parts that come in
2486 // a non-deterministic order. pid is the thread id.
2487 if (log)
2488 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2489 __FUNCTION__, GetID (), pid);
2490
2491 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002492 bool created_now = false;
2493 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002494 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2495
2496 // 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 +00002497 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002498 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002499 // We can now resume the newly created thread since it is fully created.
2500 NotifyThreadCreateStopped (pid);
2501 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002502 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002503 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002504 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002505 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002506 },
2507 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002508 }
2509 else
2510 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002511 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2512 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002513 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002514 }
2515
Todd Fiala58a2f662014-08-12 17:02:07 +00002516 // Done handling.
2517 return;
2518 }
2519
2520 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002521 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002522 {
2523 // This is a tgkill()-based stop.
2524 if (thread_sp)
2525 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002526 if (log)
2527 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2528 __FUNCTION__,
2529 GetID (),
2530 pid);
2531
Chaoren Linaab58632015-02-03 01:50:57 +00002532 // Check that we're not already marked with a stop reason.
2533 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2534 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2535 // and that, without an intervening resume, we received another stop. It is more likely
2536 // that we are missing the marking of a run state somewhere if we find that the thread was
2537 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002538 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2539 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002540
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002541 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002542 if (!StateIsStoppedState (thread_state, false))
2543 {
2544 // An inferior thread just stopped, but was not the primary cause of the process stop.
2545 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2546 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002547 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002548 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002549 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002550 }
2551 else
2552 {
2553 if (log)
2554 {
2555 // Retrieve the signal name if the thread was stopped by a signal.
2556 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002557 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002558 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2559 if (!signal_name)
2560 signal_name = "<no-signal-name>";
2561
2562 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",
2563 __FUNCTION__,
2564 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002565 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002566 StateAsCString (thread_state),
2567 stop_signo,
2568 signal_name);
2569 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002570 // Tell the thread state coordinator about the stop.
2571 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002572 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002573 }
2574
2575 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002576 return;
2577 }
2578
2579 if (log)
2580 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2581
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002582 // This thread is stopped.
2583 NotifyThreadStop (pid);
2584
Todd Fialaaf245d12014-06-30 21:05:18 +00002585 switch (signo)
2586 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002587 case SIGSTOP:
2588 {
2589 if (log)
2590 {
2591 if (is_from_llgs)
2592 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2593 else
2594 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2595 }
2596
Chaoren Linfa03ad22015-02-03 01:50:42 +00002597 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2598 // This thread will get stopped again as part of the group-stop completion.
2599 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002600 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002601 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002602 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002603 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002604 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002605 },
2606 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002607 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002608 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002609 case SIGSEGV:
2610 case SIGILL:
2611 case SIGFPE:
2612 case SIGBUS:
2613 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002614 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002615 break;
2616 default:
2617 // This is just a pre-signal-delivery notification of the incoming signal.
2618 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002619 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002620
2621 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002622 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002623
2624 // Send a stop to the debugger after we get all other threads to stop.
2625 CallAfterRunningThreadsStop (pid,
2626 [=] (lldb::tid_t signaling_tid)
2627 {
2628 SetCurrentThreadID (signaling_tid);
2629 SetState (StateType::eStateStopped, true);
2630 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002631}
2632
2633Error
2634NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2635{
Todd Fialaaf245d12014-06-30 21:05:18 +00002636 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2637 if (log)
2638 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2639
Chaoren Lin03f12d62015-02-03 01:50:49 +00002640 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2641 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002642 int deferred_signo = 0;
2643 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002644 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002645
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002646 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002647
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002648 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002649 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002650 assert (thread_sp && "thread list should not contain NULL threads");
2651
2652 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2653
2654 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002655 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002656 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002657 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2658 __FUNCTION__, GetID (), thread_sp->GetID ());
2659 continue;
2660 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002661
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002662 if (log)
2663 {
2664 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2665 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2666 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002667
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002668 switch (action->state)
2669 {
2670 case eStateRunning:
2671 {
2672 // Run the thread, possibly feeding it the signal.
2673 const int signo = action->signal;
2674 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2675 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2676 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002677 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002678 // Pass this signal number on to the inferior to handle.
2679 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2680 if (resume_result.Success())
2681 SetState(eStateRunning, true);
2682 return resume_result;
2683 },
2684 CoordinatorErrorHandler);
2685 break;
2686 }
2687
2688 case eStateStepping:
2689 {
2690 // Request the step.
2691 const int signo = action->signal;
2692 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2693 [=](lldb::tid_t tid_to_step, bool supress_signal)
2694 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002695 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002696 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2697 assert (step_result.Success() && "SingleStep() failed");
2698 if (step_result.Success())
2699 SetState(eStateStepping, true);
2700 return step_result;
2701 },
2702 CoordinatorErrorHandler);
2703 stepping = true;
2704 break;
2705 }
2706
2707 case eStateSuspended:
2708 case eStateStopped:
2709 // if we haven't chosen a deferred signal tid yet, use this one.
2710 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002711 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002712 deferred_signal_tid = thread_sp->GetID ();
2713 deferred_signal_thread_sp = thread_sp;
2714 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002715 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002716 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002717
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002718 default:
2719 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2720 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002721 }
2722 }
2723
Chaoren Linfa03ad22015-02-03 01:50:42 +00002724 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2725 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002726 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2727 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002728 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002729 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2730 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002731 [=](lldb::tid_t deferred_notification_tid)
2732 {
Chaoren Linae29d392015-02-03 01:50:46 +00002733 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002734 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002735
2736 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002737 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00002738
2739 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002740 SetState (StateType::eStateStopped, true);
2741 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002742 }
2743
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002744 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002745}
2746
2747Error
2748NativeProcessLinux::Halt ()
2749{
2750 Error error;
2751
Todd Fialaaf245d12014-06-30 21:05:18 +00002752 if (kill (GetID (), SIGSTOP) != 0)
2753 error.SetErrorToErrno ();
2754
2755 return error;
2756}
2757
2758Error
2759NativeProcessLinux::Detach ()
2760{
2761 Error error;
2762
2763 // Tell ptrace to detach from the process.
2764 if (GetID () != LLDB_INVALID_PROCESS_ID)
2765 error = Detach (GetID ());
2766
2767 // Stop monitoring the inferior.
2768 StopMonitor ();
2769
2770 // No error.
2771 return error;
2772}
2773
2774Error
2775NativeProcessLinux::Signal (int signo)
2776{
2777 Error error;
2778
2779 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2780 if (log)
2781 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2782 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2783
2784 if (kill(GetID(), signo))
2785 error.SetErrorToErrno();
2786
2787 return error;
2788}
2789
2790Error
Chaoren Line9547b82015-02-03 01:51:00 +00002791NativeProcessLinux::Interrupt ()
2792{
2793 // Pick a running thread (or if none, a not-dead stopped thread) as
2794 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002795 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2796
2797 NativeThreadProtocolSP running_thread_sp;
2798 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002799
2800 if (log)
2801 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2802
2803 Mutex::Locker locker (m_threads_mutex);
2804
2805 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002806 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002807 // The thread shouldn't be null but lets just cover that here.
2808 if (!thread_sp)
2809 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002810
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002811 // If we have a running or stepping thread, we'll call that the
2812 // target of the interrupt.
2813 const auto thread_state = thread_sp->GetState ();
2814 if (thread_state == eStateRunning ||
2815 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002816 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002817 running_thread_sp = thread_sp;
2818 break;
2819 }
2820 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2821 {
2822 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2823 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002824 }
2825 }
2826
2827 if (!running_thread_sp && !stopped_thread_sp)
2828 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002829 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002830 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002831 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002832
Chaoren Line9547b82015-02-03 01:51:00 +00002833 return error;
2834 }
2835
2836 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2837
2838 if (log)
2839 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2840 __FUNCTION__,
2841 GetID (),
2842 running_thread_sp ? "running" : "stopped",
2843 deferred_signal_thread_sp->GetID ());
2844
2845 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2846 [=](lldb::tid_t deferred_notification_tid)
2847 {
2848 // Set the signal thread to the current thread.
2849 SetCurrentThreadID (deferred_notification_tid);
2850
2851 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002852 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00002853
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002854 // Tell the process delegate that the process is in a stopped state.
2855 SetState (StateType::eStateStopped, true);
2856 });
2857 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002858}
2859
2860Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002861NativeProcessLinux::Kill ()
2862{
2863 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2864 if (log)
2865 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2866
2867 Error error;
2868
2869 switch (m_state)
2870 {
2871 case StateType::eStateInvalid:
2872 case StateType::eStateExited:
2873 case StateType::eStateCrashed:
2874 case StateType::eStateDetached:
2875 case StateType::eStateUnloaded:
2876 // Nothing to do - the process is already dead.
2877 if (log)
2878 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2879 return error;
2880
2881 case StateType::eStateConnected:
2882 case StateType::eStateAttaching:
2883 case StateType::eStateLaunching:
2884 case StateType::eStateStopped:
2885 case StateType::eStateRunning:
2886 case StateType::eStateStepping:
2887 case StateType::eStateSuspended:
2888 // We can try to kill a process in these states.
2889 break;
2890 }
2891
2892 if (kill (GetID (), SIGKILL) != 0)
2893 {
2894 error.SetErrorToErrno ();
2895 return error;
2896 }
2897
2898 return error;
2899}
2900
2901static Error
2902ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2903{
2904 memory_region_info.Clear();
2905
2906 StringExtractor line_extractor (maps_line.c_str ());
2907
2908 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2909 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2910
2911 // Parse out the starting address
2912 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2913
2914 // Parse out hyphen separating start and end address from range.
2915 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2916 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2917
2918 // Parse out the ending address
2919 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2920
2921 // Parse out the space after the address.
2922 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2923 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2924
2925 // Save the range.
2926 memory_region_info.GetRange ().SetRangeBase (start_address);
2927 memory_region_info.GetRange ().SetRangeEnd (end_address);
2928
2929 // Parse out each permission entry.
2930 if (line_extractor.GetBytesLeft () < 4)
2931 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2932
2933 // Handle read permission.
2934 const char read_perm_char = line_extractor.GetChar ();
2935 if (read_perm_char == 'r')
2936 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2937 else
2938 {
2939 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2940 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2941 }
2942
2943 // Handle write permission.
2944 const char write_perm_char = line_extractor.GetChar ();
2945 if (write_perm_char == 'w')
2946 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2947 else
2948 {
2949 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2950 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2951 }
2952
2953 // Handle execute permission.
2954 const char exec_perm_char = line_extractor.GetChar ();
2955 if (exec_perm_char == 'x')
2956 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2957 else
2958 {
2959 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2960 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2961 }
2962
2963 return Error ();
2964}
2965
2966Error
2967NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2968{
2969 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2970 // with no perms if it is not mapped.
2971
2972 // Use an approach that reads memory regions from /proc/{pid}/maps.
2973 // Assume proc maps entries are in ascending order.
2974 // FIXME assert if we find differently.
2975 Mutex::Locker locker (m_mem_region_cache_mutex);
2976
2977 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2978 Error error;
2979
2980 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2981 {
2982 // We're done.
2983 error.SetErrorString ("unsupported");
2984 return error;
2985 }
2986
2987 // If our cache is empty, pull the latest. There should always be at least one memory region
2988 // if memory region handling is supported.
2989 if (m_mem_region_cache.empty ())
2990 {
2991 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2992 [&] (const std::string &line) -> bool
2993 {
2994 MemoryRegionInfo info;
2995 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2996 if (parse_error.Success ())
2997 {
2998 m_mem_region_cache.push_back (info);
2999 return true;
3000 }
3001 else
3002 {
3003 if (log)
3004 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3005 return false;
3006 }
3007 });
3008
3009 // If we had an error, we'll mark unsupported.
3010 if (error.Fail ())
3011 {
3012 m_supports_mem_region = LazyBool::eLazyBoolNo;
3013 return error;
3014 }
3015 else if (m_mem_region_cache.empty ())
3016 {
3017 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3018 // is supported. Assume we don't support map entries via procfs.
3019 if (log)
3020 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3021 m_supports_mem_region = LazyBool::eLazyBoolNo;
3022 error.SetErrorString ("not supported");
3023 return error;
3024 }
3025
3026 if (log)
3027 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3028
3029 // We support memory retrieval, remember that.
3030 m_supports_mem_region = LazyBool::eLazyBoolYes;
3031 }
3032 else
3033 {
3034 if (log)
3035 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3036 }
3037
3038 lldb::addr_t prev_base_address = 0;
3039
3040 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3041 // There can be a ton of regions on pthreads apps with lots of threads.
3042 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3043 {
3044 MemoryRegionInfo &proc_entry_info = *it;
3045
3046 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3047 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3048 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3049
3050 // If the target address comes before this entry, indicate distance to next region.
3051 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3052 {
3053 range_info.GetRange ().SetRangeBase (load_addr);
3054 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3055 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3056 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3057 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3058
3059 return error;
3060 }
3061 else if (proc_entry_info.GetRange ().Contains (load_addr))
3062 {
3063 // The target address is within the memory region we're processing here.
3064 range_info = proc_entry_info;
3065 return error;
3066 }
3067
3068 // The target memory address comes somewhere after the region we just parsed.
3069 }
3070
3071 // If we made it here, we didn't find an entry that contained the given address.
3072 error.SetErrorString ("address comes after final region");
3073
3074 if (log)
3075 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3076
3077 return error;
3078}
3079
3080void
3081NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3082{
3083 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3084 if (log)
3085 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3086
3087 {
3088 Mutex::Locker locker (m_mem_region_cache_mutex);
3089 if (log)
3090 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3091 m_mem_region_cache.clear ();
3092 }
3093}
3094
3095Error
3096NativeProcessLinux::AllocateMemory (
3097 lldb::addr_t size,
3098 uint32_t permissions,
3099 lldb::addr_t &addr)
3100{
3101 // FIXME implementing this requires the equivalent of
3102 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3103 // functional ThreadPlans working with Native*Protocol.
3104#if 1
3105 return Error ("not implemented yet");
3106#else
3107 addr = LLDB_INVALID_ADDRESS;
3108
3109 unsigned prot = 0;
3110 if (permissions & lldb::ePermissionsReadable)
3111 prot |= eMmapProtRead;
3112 if (permissions & lldb::ePermissionsWritable)
3113 prot |= eMmapProtWrite;
3114 if (permissions & lldb::ePermissionsExecutable)
3115 prot |= eMmapProtExec;
3116
3117 // TODO implement this directly in NativeProcessLinux
3118 // (and lift to NativeProcessPOSIX if/when that class is
3119 // refactored out).
3120 if (InferiorCallMmap(this, addr, 0, size, prot,
3121 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3122 m_addr_to_mmap_size[addr] = size;
3123 return Error ();
3124 } else {
3125 addr = LLDB_INVALID_ADDRESS;
3126 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3127 }
3128#endif
3129}
3130
3131Error
3132NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3133{
3134 // FIXME see comments in AllocateMemory - required lower-level
3135 // bits not in place yet (ThreadPlans)
3136 return Error ("not implemented");
3137}
3138
3139lldb::addr_t
3140NativeProcessLinux::GetSharedLibraryInfoAddress ()
3141{
3142#if 1
3143 // punt on this for now
3144 return LLDB_INVALID_ADDRESS;
3145#else
3146 // Return the image info address for the exe module
3147#if 1
3148 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3149
3150 ModuleSP module_sp;
3151 Error error = GetExeModuleSP (module_sp);
3152 if (error.Fail ())
3153 {
3154 if (log)
3155 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3156 return LLDB_INVALID_ADDRESS;
3157 }
3158
3159 if (module_sp == nullptr)
3160 {
3161 if (log)
3162 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3163 return LLDB_INVALID_ADDRESS;
3164 }
3165
3166 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3167 if (object_file_sp == nullptr)
3168 {
3169 if (log)
3170 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3171 return LLDB_INVALID_ADDRESS;
3172 }
3173
3174 return obj_file_sp->GetImageInfoAddress();
3175#else
3176 Target *target = &GetTarget();
3177 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3178 Address addr = obj_file->GetImageInfoAddress(target);
3179
3180 if (addr.IsValid())
3181 return addr.GetLoadAddress(target);
3182 return LLDB_INVALID_ADDRESS;
3183#endif
3184#endif // punt on this for now
3185}
3186
3187size_t
3188NativeProcessLinux::UpdateThreads ()
3189{
3190 // The NativeProcessLinux monitoring threads are always up to date
3191 // with respect to thread state and they keep the thread list
3192 // populated properly. All this method needs to do is return the
3193 // thread count.
3194 Mutex::Locker locker (m_threads_mutex);
3195 return m_threads.size ();
3196}
3197
3198bool
3199NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3200{
3201 arch = m_arch;
3202 return true;
3203}
3204
3205Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003206NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003207{
3208 // FIXME put this behind a breakpoint protocol class that can be
3209 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003210 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003211 static const uint8_t g_i386_opcode [] = { 0xCC };
3212
3213 switch (m_arch.GetMachine ())
3214 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003215 case llvm::Triple::aarch64:
3216 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3217 return Error ();
3218
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003219 case llvm::Triple::arm:
3220 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3221 return Error ();
3222
Todd Fialaaf245d12014-06-30 21:05:18 +00003223 case llvm::Triple::x86:
3224 case llvm::Triple::x86_64:
3225 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3226 return Error ();
3227
3228 default:
3229 assert(false && "CPU type not supported!");
3230 return Error ("CPU type not supported");
3231 }
3232}
3233
3234Error
3235NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3236{
3237 if (hardware)
3238 return Error ("NativeProcessLinux does not support hardware breakpoints");
3239 else
3240 return SetSoftwareBreakpoint (addr, size);
3241}
3242
3243Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003244NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3245 size_t &actual_opcode_size,
3246 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003247{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003248 // FIXME put this behind a breakpoint protocol class that can be set per
3249 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003250 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003251 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3252 // linux kernel does otherwise.
3253 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003254 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003255 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003256 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003257 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003258
3259 switch (m_arch.GetMachine ())
3260 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003261 case llvm::Triple::aarch64:
3262 trap_opcode_bytes = g_aarch64_opcode;
3263 actual_opcode_size = sizeof(g_aarch64_opcode);
3264 return Error ();
3265
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003266 case llvm::Triple::arm:
3267 switch (trap_opcode_size_hint)
3268 {
3269 case 2:
3270 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3271 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3272 return Error ();
3273 case 4:
3274 trap_opcode_bytes = g_arm_breakpoint_opcode;
3275 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3276 return Error ();
3277 default:
3278 assert(false && "Unrecognised trap opcode size hint!");
3279 return Error ("Unrecognised trap opcode size hint!");
3280 }
3281
Todd Fialaaf245d12014-06-30 21:05:18 +00003282 case llvm::Triple::x86:
3283 case llvm::Triple::x86_64:
3284 trap_opcode_bytes = g_i386_opcode;
3285 actual_opcode_size = sizeof(g_i386_opcode);
3286 return Error ();
3287
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003288 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003289 trap_opcode_bytes = g_mips64_opcode;
3290 actual_opcode_size = sizeof(g_mips64_opcode);
3291 return Error ();
3292
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003293 case llvm::Triple::mips64el:
3294 trap_opcode_bytes = g_mips64el_opcode;
3295 actual_opcode_size = sizeof(g_mips64el_opcode);
3296 return Error ();
3297
Todd Fialaaf245d12014-06-30 21:05:18 +00003298 default:
3299 assert(false && "CPU type not supported!");
3300 return Error ("CPU type not supported");
3301 }
3302}
3303
3304#if 0
3305ProcessMessage::CrashReason
3306NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3307{
3308 ProcessMessage::CrashReason reason;
3309 assert(info->si_signo == SIGSEGV);
3310
3311 reason = ProcessMessage::eInvalidCrashReason;
3312
3313 switch (info->si_code)
3314 {
3315 default:
3316 assert(false && "unexpected si_code for SIGSEGV");
3317 break;
3318 case SI_KERNEL:
3319 // Linux will occasionally send spurious SI_KERNEL codes.
3320 // (this is poorly documented in sigaction)
3321 // One way to get this is via unaligned SIMD loads.
3322 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3323 break;
3324 case SEGV_MAPERR:
3325 reason = ProcessMessage::eInvalidAddress;
3326 break;
3327 case SEGV_ACCERR:
3328 reason = ProcessMessage::ePrivilegedAddress;
3329 break;
3330 }
3331
3332 return reason;
3333}
3334#endif
3335
3336
3337#if 0
3338ProcessMessage::CrashReason
3339NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3340{
3341 ProcessMessage::CrashReason reason;
3342 assert(info->si_signo == SIGILL);
3343
3344 reason = ProcessMessage::eInvalidCrashReason;
3345
3346 switch (info->si_code)
3347 {
3348 default:
3349 assert(false && "unexpected si_code for SIGILL");
3350 break;
3351 case ILL_ILLOPC:
3352 reason = ProcessMessage::eIllegalOpcode;
3353 break;
3354 case ILL_ILLOPN:
3355 reason = ProcessMessage::eIllegalOperand;
3356 break;
3357 case ILL_ILLADR:
3358 reason = ProcessMessage::eIllegalAddressingMode;
3359 break;
3360 case ILL_ILLTRP:
3361 reason = ProcessMessage::eIllegalTrap;
3362 break;
3363 case ILL_PRVOPC:
3364 reason = ProcessMessage::ePrivilegedOpcode;
3365 break;
3366 case ILL_PRVREG:
3367 reason = ProcessMessage::ePrivilegedRegister;
3368 break;
3369 case ILL_COPROC:
3370 reason = ProcessMessage::eCoprocessorError;
3371 break;
3372 case ILL_BADSTK:
3373 reason = ProcessMessage::eInternalStackError;
3374 break;
3375 }
3376
3377 return reason;
3378}
3379#endif
3380
3381#if 0
3382ProcessMessage::CrashReason
3383NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3384{
3385 ProcessMessage::CrashReason reason;
3386 assert(info->si_signo == SIGFPE);
3387
3388 reason = ProcessMessage::eInvalidCrashReason;
3389
3390 switch (info->si_code)
3391 {
3392 default:
3393 assert(false && "unexpected si_code for SIGFPE");
3394 break;
3395 case FPE_INTDIV:
3396 reason = ProcessMessage::eIntegerDivideByZero;
3397 break;
3398 case FPE_INTOVF:
3399 reason = ProcessMessage::eIntegerOverflow;
3400 break;
3401 case FPE_FLTDIV:
3402 reason = ProcessMessage::eFloatDivideByZero;
3403 break;
3404 case FPE_FLTOVF:
3405 reason = ProcessMessage::eFloatOverflow;
3406 break;
3407 case FPE_FLTUND:
3408 reason = ProcessMessage::eFloatUnderflow;
3409 break;
3410 case FPE_FLTRES:
3411 reason = ProcessMessage::eFloatInexactResult;
3412 break;
3413 case FPE_FLTINV:
3414 reason = ProcessMessage::eFloatInvalidOperation;
3415 break;
3416 case FPE_FLTSUB:
3417 reason = ProcessMessage::eFloatSubscriptRange;
3418 break;
3419 }
3420
3421 return reason;
3422}
3423#endif
3424
3425#if 0
3426ProcessMessage::CrashReason
3427NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3428{
3429 ProcessMessage::CrashReason reason;
3430 assert(info->si_signo == SIGBUS);
3431
3432 reason = ProcessMessage::eInvalidCrashReason;
3433
3434 switch (info->si_code)
3435 {
3436 default:
3437 assert(false && "unexpected si_code for SIGBUS");
3438 break;
3439 case BUS_ADRALN:
3440 reason = ProcessMessage::eIllegalAlignment;
3441 break;
3442 case BUS_ADRERR:
3443 reason = ProcessMessage::eIllegalAddress;
3444 break;
3445 case BUS_OBJERR:
3446 reason = ProcessMessage::eHardwareError;
3447 break;
3448 }
3449
3450 return reason;
3451}
3452#endif
3453
3454void
3455NativeProcessLinux::ServeOperation(OperationArgs *args)
3456{
3457 NativeProcessLinux *monitor = args->m_monitor;
3458
3459 // We are finised with the arguments and are ready to go. Sync with the
3460 // parent thread and start serving operations on the inferior.
3461 sem_post(&args->m_semaphore);
3462
3463 for(;;)
3464 {
3465 // wait for next pending operation
3466 if (sem_wait(&monitor->m_operation_pending))
3467 {
3468 if (errno == EINTR)
3469 continue;
3470 assert(false && "Unexpected errno from sem_wait");
3471 }
3472
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003473 // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3474 // android. We don't have to send a post to the m_operation_done semaphore because in this
3475 // case the synchronization is achieved by a Join() call
3476 if (monitor->m_operation == EXIT_OPERATION)
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003477 break;
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003478
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003479 static_cast<Operation*>(monitor->m_operation)->Execute(monitor);
Todd Fialaaf245d12014-06-30 21:05:18 +00003480
3481 // notify calling thread that operation is complete
3482 sem_post(&monitor->m_operation_done);
3483 }
3484}
3485
3486void
3487NativeProcessLinux::DoOperation(void *op)
3488{
3489 Mutex::Locker lock(m_operation_mutex);
3490
3491 m_operation = op;
3492
3493 // notify operation thread that an operation is ready to be processed
3494 sem_post(&m_operation_pending);
3495
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003496 // Don't wait for the operation to complete in case of an exit operation. The operation thread
3497 // will exit without posting to the semaphore
3498 if (m_operation == EXIT_OPERATION)
3499 return;
3500
Todd Fialaaf245d12014-06-30 21:05:18 +00003501 // wait for operation to complete
3502 while (sem_wait(&m_operation_done))
3503 {
3504 if (errno == EINTR)
3505 continue;
3506 assert(false && "Unexpected errno from sem_wait");
3507 }
3508}
3509
3510Error
3511NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3512{
3513 ReadOperation op(addr, buf, size, bytes_read);
3514 DoOperation(&op);
3515 return op.GetError ();
3516}
3517
3518Error
3519NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3520{
3521 WriteOperation op(addr, buf, size, bytes_written);
3522 DoOperation(&op);
3523 return op.GetError ();
3524}
3525
Chaoren Lin97ccc292015-02-03 01:51:12 +00003526Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003527NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003528 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003529{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003530 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003531 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003532 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003533}
3534
Chaoren Lin97ccc292015-02-03 01:51:12 +00003535Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003536NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3537 const char* reg_name, const RegisterValue &value)
3538{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003539 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003540 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003541 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003542}
3543
Chaoren Lin97ccc292015-02-03 01:51:12 +00003544Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003545NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3546{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003547 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003548 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003549 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003550}
3551
Chaoren Lin97ccc292015-02-03 01:51:12 +00003552Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003553NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3554{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003555 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003556 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003557 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003558}
3559
Chaoren Lin97ccc292015-02-03 01:51:12 +00003560Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003561NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3562{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003563 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003564 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003565 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003566}
3567
Chaoren Lin97ccc292015-02-03 01:51:12 +00003568Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003569NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3570{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003571 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003572 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003573 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003574}
3575
Chaoren Lin97ccc292015-02-03 01:51:12 +00003576Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003577NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3578{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003579 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003580 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003581 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003582}
3583
Chaoren Lin97ccc292015-02-03 01:51:12 +00003584Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003585NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3586{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003587 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003588 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003589 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003590}
3591
Chaoren Lin97ccc292015-02-03 01:51:12 +00003592Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003593NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3594{
Todd Fialaaf245d12014-06-30 21:05:18 +00003595 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3596
3597 if (log)
3598 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3599 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003600 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003601 DoOperation (&op);
3602 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003603 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3604 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003605}
3606
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00003607#if defined(__arm__)
3608
3609namespace {
3610
3611struct EmulatorBaton
3612{
3613 NativeProcessLinux* m_process;
3614 NativeRegisterContext* m_reg_context;
3615 RegisterValue m_pc;
3616 RegisterValue m_cpsr;
3617
3618 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
3619 m_process(process), m_reg_context(reg_context) {}
3620};
3621
3622} // anonymous namespace
3623
3624static size_t
3625ReadMemoryCallback (EmulateInstruction *instruction,
3626 void *baton,
3627 const EmulateInstruction::Context &context,
3628 lldb::addr_t addr,
3629 void *dst,
3630 size_t length)
3631{
3632 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3633
3634 lldb::addr_t bytes_read;
3635 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
3636 return bytes_read;
3637}
3638
3639static bool
3640ReadRegisterCallback (EmulateInstruction *instruction,
3641 void *baton,
3642 const RegisterInfo *reg_info,
3643 RegisterValue &reg_value)
3644{
3645 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3646
3647 // The emulator only fill in the dwarf regsiter numbers (and in some case
3648 // the generic register numbers). Get the full register info from the
3649 // register context based on the dwarf register numbers.
3650 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
3651 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
3652
3653 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
3654 return error.Success();
3655}
3656
3657static bool
3658WriteRegisterCallback (EmulateInstruction *instruction,
3659 void *baton,
3660 const EmulateInstruction::Context &context,
3661 const RegisterInfo *reg_info,
3662 const RegisterValue &reg_value)
3663{
3664 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3665
3666 switch (reg_info->kinds[eRegisterKindGeneric])
3667 {
3668 case LLDB_REGNUM_GENERIC_PC:
3669 emulator_baton->m_pc = reg_value;
3670 break;
3671 case LLDB_REGNUM_GENERIC_FLAGS:
3672 emulator_baton->m_cpsr = reg_value;
3673 break;
3674 }
3675
3676 return true;
3677}
3678
3679static size_t WriteMemoryCallback (EmulateInstruction *instruction,
3680 void *baton,
3681 const EmulateInstruction::Context &context,
3682 lldb::addr_t addr,
3683 const void *dst,
3684 size_t length)
3685{
3686 return length;
3687}
3688
3689Error
3690NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3691{
3692 Error error;
3693 NativeRegisterContextSP register_context_sp = GetThreadByID(tid)->GetRegisterContext();
3694
3695 std::unique_ptr<EmulateInstruction> emulator_ap(
3696 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
3697
3698 if (emulator_ap == nullptr)
3699 return Error("Instrunction emulator not found!");
3700
3701 EmulatorBaton baton(this, register_context_sp.get());
3702 emulator_ap->SetBaton(&baton);
3703 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
3704 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
3705 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
3706 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
3707
3708 if (!emulator_ap->ReadInstruction())
3709 return Error("Read instruction failed!");
3710
3711 if (!emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC))
3712 return Error("Evaluate instrcution failed!");
3713
3714 lldb::addr_t next_pc = baton.m_pc.GetAsUInt32();
3715 lldb::addr_t next_cpsr = 0;
3716 if (baton.m_cpsr.GetType() != RegisterValue::eTypeInvalid)
3717 {
3718 next_cpsr = baton.m_cpsr.GetAsUInt32();
3719 }
3720 else
3721 {
3722 const RegisterInfo* cpsr_info = register_context_sp->GetRegisterInfo(
3723 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
3724 next_cpsr = register_context_sp->ReadRegisterAsUnsigned(cpsr_info, LLDB_INVALID_ADDRESS);
3725 }
3726
3727 if (next_cpsr & 0x20)
3728 {
3729 // Thumb mode
3730 error = SetBreakpoint(next_pc, 2, false);
3731 }
3732 else
3733 {
3734 // Arm mode
3735 error = SetBreakpoint(next_pc, 4, false);
3736 }
3737
3738 if (error.Fail())
3739 return error;
3740
3741 m_threads_stepping_with_breakpoint.emplace(tid, next_pc);
3742
3743 error = Resume(tid, signo);
3744 if (error.Fail())
3745 return error;
3746
3747 return Error();
3748}
3749
3750#else // defined(__arm__)
3751
Chaoren Lin97ccc292015-02-03 01:51:12 +00003752Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003753NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3754{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003755 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003756 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003757 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003758}
3759
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00003760#endif // defined(__arm__)
3761
Chaoren Lin97ccc292015-02-03 01:51:12 +00003762Error
3763NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003764{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003765 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003766 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003767 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003768}
3769
Chaoren Lin97ccc292015-02-03 01:51:12 +00003770Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003771NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3772{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003773 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003774 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003775 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003776}
3777
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003778Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003779NativeProcessLinux::Detach(lldb::tid_t tid)
3780{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003781 if (tid == LLDB_INVALID_THREAD_ID)
3782 return Error();
3783
3784 DetachOperation op(tid);
3785 DoOperation(&op);
3786 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003787}
3788
3789bool
3790NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3791{
3792 int target_fd = open(path, flags, 0666);
3793
3794 if (target_fd == -1)
3795 return false;
3796
Pavel Labath493c3a12015-02-04 10:36:57 +00003797 if (dup2(target_fd, fd) == -1)
3798 return false;
3799
3800 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003801}
3802
3803void
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003804NativeProcessLinux::StopMonitorThread()
Todd Fialaaf245d12014-06-30 21:05:18 +00003805{
Zachary Turneracee96a2014-09-23 18:32:09 +00003806 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003807 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003808 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00003809 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003810 }
3811}
3812
3813void
3814NativeProcessLinux::StopMonitor()
3815{
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003816 StopMonitorThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003817 StopCoordinatorThread ();
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003818 StopOpThread();
Todd Fialaaf245d12014-06-30 21:05:18 +00003819 sem_destroy(&m_operation_pending);
3820 sem_destroy(&m_operation_done);
3821
3822 // TODO: validate whether this still holds, fix up comment.
3823 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3824 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3825 // the descriptor to a ConnectionFileDescriptor object. Consequently
3826 // even though still has the file descriptor, we shouldn't close it here.
3827}
3828
3829void
3830NativeProcessLinux::StopOpThread()
3831{
Zachary Turneracee96a2014-09-23 18:32:09 +00003832 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003833 return;
3834
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003835 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00003836 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003837}
3838
Chaoren Linfa03ad22015-02-03 01:50:42 +00003839Error
3840NativeProcessLinux::StartCoordinatorThread ()
3841{
3842 Error error;
3843 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3844 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3845
3846 // Skip if thread is already running
3847 if (m_coordinator_thread.IsJoinable())
3848 {
3849 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3850 if (log)
3851 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3852 return error;
3853 }
3854
3855 // Enable verbose logging if lldb thread logging is enabled.
3856 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3857
3858 if (log)
3859 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3860 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3861 return error;
3862}
3863
3864void *
3865NativeProcessLinux::CoordinatorThread (void *arg)
3866{
3867 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3868
3869 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3870 assert (process && "null process passed to CoordinatorThread");
3871 if (!process)
3872 {
3873 if (log)
3874 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3875 return nullptr;
3876 }
3877
3878 // Run the thread state coordinator loop until it is done. This call uses
3879 // efficient waiting for an event to be ready.
3880 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3881 {
3882 }
3883
3884 if (log)
3885 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3886
3887 return nullptr;
3888}
3889
3890void
3891NativeProcessLinux::StopCoordinatorThread()
3892{
3893 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3894 if (log)
3895 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3896
3897 // Tell the coordinator we're done. This will cause the coordinator
3898 // run loop thread to exit when the processing queue hits this message.
3899 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003900 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003901}
3902
Todd Fialaaf245d12014-06-30 21:05:18 +00003903bool
3904NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3905{
3906 for (auto thread_sp : m_threads)
3907 {
3908 assert (thread_sp && "thread list should not contain NULL threads");
3909 if (thread_sp->GetID () == thread_id)
3910 {
3911 // We have this thread.
3912 return true;
3913 }
3914 }
3915
3916 // We don't have this thread.
3917 return false;
3918}
3919
3920NativeThreadProtocolSP
3921NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3922{
3923 // CONSIDER organize threads by map - we can do better than linear.
3924 for (auto thread_sp : m_threads)
3925 {
3926 if (thread_sp->GetID () == thread_id)
3927 return thread_sp;
3928 }
3929
3930 // We don't have this thread.
3931 return NativeThreadProtocolSP ();
3932}
3933
3934bool
3935NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3936{
3937 Mutex::Locker locker (m_threads_mutex);
3938 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3939 {
3940 if (*it && ((*it)->GetID () == thread_id))
3941 {
3942 m_threads.erase (it);
3943 return true;
3944 }
3945 }
3946
3947 // Didn't find it.
3948 return false;
3949}
3950
3951NativeThreadProtocolSP
3952NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3953{
3954 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3955
3956 Mutex::Locker locker (m_threads_mutex);
3957
3958 if (log)
3959 {
3960 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3961 __FUNCTION__,
3962 GetID (),
3963 thread_id);
3964 }
3965
3966 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3967
3968 // If this is the first thread, save it as the current thread
3969 if (m_threads.empty ())
3970 SetCurrentThreadID (thread_id);
3971
3972 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3973 m_threads.push_back (thread_sp);
3974
3975 return thread_sp;
3976}
3977
3978NativeThreadProtocolSP
3979NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3980{
3981 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3982
3983 Mutex::Locker locker (m_threads_mutex);
3984 if (log)
3985 {
3986 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3987 __FUNCTION__,
3988 GetID (),
3989 thread_id);
3990 }
3991
3992 // Retrieve the thread if it is already getting tracked.
3993 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3994 if (thread_sp)
3995 {
3996 if (log)
3997 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3998 __FUNCTION__,
3999 GetID (),
4000 thread_id);
4001 created = false;
4002 return thread_sp;
4003
4004 }
4005
4006 // Create the thread metadata since it isn't being tracked.
4007 if (log)
4008 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
4009 __FUNCTION__,
4010 GetID (),
4011 thread_id);
4012
4013 thread_sp.reset (new NativeThreadLinux (this, thread_id));
4014 m_threads.push_back (thread_sp);
4015 created = true;
4016
4017 return thread_sp;
4018}
4019
4020Error
4021NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4022{
Todd Fiala75f47c32014-10-11 21:42:09 +00004023 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00004024
4025 Error error;
4026
4027 // Get a linux thread pointer.
4028 if (!thread_sp)
4029 {
4030 error.SetErrorString ("null thread_sp");
4031 if (log)
4032 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4033 return error;
4034 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004035 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00004036
4037 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004038 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00004039 if (!context_sp)
4040 {
4041 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4042 if (log)
4043 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4044 return error;
4045 }
4046
4047 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00004048 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00004049 if (error.Fail ())
4050 {
4051 if (log)
4052 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4053 return error;
4054 }
4055 else
4056 {
4057 if (log)
4058 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4059 }
4060
4061 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4062 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4063 lldb::addr_t breakpoint_addr = initial_pc_addr;
4064 if (breakpoint_size > static_cast<lldb::addr_t> (0))
4065 {
4066 // Do not allow breakpoint probe to wrap around.
4067 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
4068 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
4069 }
4070
4071 // Check if we stopped because of a breakpoint.
4072 NativeBreakpointSP breakpoint_sp;
4073 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4074 if (!error.Success () || !breakpoint_sp)
4075 {
4076 // We didn't find one at a software probe location. Nothing to do.
4077 if (log)
4078 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4079 return Error ();
4080 }
4081
4082 // If the breakpoint is not a software breakpoint, nothing to do.
4083 if (!breakpoint_sp->IsSoftwareBreakpoint ())
4084 {
4085 if (log)
4086 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4087 return Error ();
4088 }
4089
4090 //
4091 // We have a software breakpoint and need to adjust the PC.
4092 //
4093
4094 // Sanity check.
4095 if (breakpoint_size == 0)
4096 {
4097 // Nothing to do! How did we get here?
4098 if (log)
4099 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);
4100 return Error ();
4101 }
4102
4103 // Change the program counter.
4104 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004105 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00004106
4107 error = context_sp->SetPC (breakpoint_addr);
4108 if (error.Fail ())
4109 {
4110 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004111 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00004112 return error;
4113 }
4114
4115 return error;
4116}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004117
4118void
4119NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
4120{
4121 const bool is_stopped = true;
4122 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
4123}
4124
4125void
4126NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
4127{
4128 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
4129}
4130
4131void
4132NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
4133{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004134 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004135}
4136
4137void
4138NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
4139 const std::function<void (lldb::tid_t tid)> &call_after_function)
4140{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004141 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4142 if (log)
4143 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
4144
Chaoren Linfa03ad22015-02-03 01:50:42 +00004145 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00004146 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00004147 [=](lldb::tid_t request_stop_tid)
4148 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00004149 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004150 },
4151 call_after_function,
4152 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00004153}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004154
Chaoren Lin03f12d62015-02-03 01:50:49 +00004155void
4156NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
4157 lldb::tid_t skip_stop_request_tid,
4158 const std::function<void (lldb::tid_t tid)> &call_after_function)
4159{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004160 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4161 if (log)
4162 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
4163
Chaoren Lin03f12d62015-02-03 01:50:49 +00004164 const lldb::pid_t pid = GetID ();
4165 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
4166 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
4167 [=](lldb::tid_t request_stop_tid)
4168 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00004169 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00004170 },
4171 call_after_function,
4172 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004173}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004174
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004175Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004176NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
4177{
4178 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4179 if (log)
4180 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
4181
4182 Error err;
4183 errno = 0;
4184 if (::tgkill (pid, tid, SIGSTOP) != 0)
4185 {
4186 err.SetErrorToErrno ();
4187 if (log)
4188 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
4189 }
4190
4191 return err;
4192}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004193
4194Error
4195NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4196{
4197 char maps_file_name[32];
4198 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4199
4200 FileSpec maps_file_spec(maps_file_name, false);
4201 if (!maps_file_spec.Exists()) {
4202 file_spec.Clear();
4203 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4204 }
4205
4206 FileSpec module_file_spec(module_path, true);
4207
4208 std::ifstream maps_file(maps_file_name);
4209 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4210 StringRef maps_data(maps_data_str.c_str());
4211
4212 while (!maps_data.empty())
4213 {
4214 StringRef maps_row;
4215 std::tie(maps_row, maps_data) = maps_data.split('\n');
4216
4217 SmallVector<StringRef, 16> maps_columns;
4218 maps_row.split(maps_columns, StringRef(" "), -1, false);
4219
4220 if (maps_columns.size() >= 6)
4221 {
4222 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4223 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4224 return Error();
4225 }
4226 }
4227
4228 file_spec.Clear();
4229 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4230 module_file_spec.GetFilename().AsCString(), GetID());
4231}