blob: 6f3aa685e6516177ea7dd842fd1b0daff88018aa [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"
27#include "lldb/Core/Error.h"
28#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000029#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/RegisterValue.h"
31#include "lldb/Core/Scalar.h"
32#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000033#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000034#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000035#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000036#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000037#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000038#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000042#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Utility/PseudoTerminal.h"
44
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000045#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000046#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000048#include "NativeThreadLinux.h"
49#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000050#include "Procfs.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000051#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000052
Tamas Berghammerd8584872015-02-06 10:57:40 +000053// System includes - They have to be included after framework includes because they define some
54// macros which collide with variable names in other modules
55#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000056#include <sys/personality.h>
57#include <sys/ptrace.h>
58#include <sys/socket.h>
59#include <sys/syscall.h>
60#include <sys/types.h>
61#include <sys/uio.h>
62#include <sys/user.h>
63#include <sys/wait.h>
64
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000065#if defined (__arm64__) || defined (__aarch64__)
66// NT_PRSTATUS and NT_FPREGSET definition
67#include <elf.h>
68#endif
69
Todd Fialacacde7d2014-09-27 16:54:22 +000070#ifdef __ANDROID__
71#define __ptrace_request int
72#define PT_DETACH PTRACE_DETACH
73#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000074
75#define DEBUG_PTRACE_MAXBYTES 20
76
77// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000078#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000079#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000080 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000081#endif
Todd Fialadda61942014-07-02 21:34:04 +000082#endif
83#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000084#ifndef PTRACE_SETREGS
85 #define PTRACE_SETREGS 13
86#endif
Todd Fialadda61942014-07-02 21:34:04 +000087#endif
88#ifndef PT_GETFPREGS
89#ifndef PTRACE_GETFPREGS
90 #define PTRACE_GETFPREGS 14
91#endif
92#endif
93#ifndef PT_SETFPREGS
94#ifndef PTRACE_SETFPREGS
95 #define PTRACE_SETFPREGS 15
96#endif
97#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000098#ifndef PTRACE_GETREGSET
99 #define PTRACE_GETREGSET 0x4204
100#endif
101#ifndef PTRACE_SETREGSET
102 #define PTRACE_SETREGSET 0x4205
103#endif
104#ifndef PTRACE_GET_THREAD_AREA
105 #define PTRACE_GET_THREAD_AREA 25
106#endif
107#ifndef PTRACE_ARCH_PRCTL
108 #define PTRACE_ARCH_PRCTL 30
109#endif
110#ifndef ARCH_GET_FS
111 #define ARCH_SET_GS 0x1001
112 #define ARCH_SET_FS 0x1002
113 #define ARCH_GET_FS 0x1003
114 #define ARCH_GET_GS 0x1004
115#endif
116
Todd Fiala0bce1b62014-08-17 00:10:50 +0000117#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000118
119// Support hardware breakpoints in case it has not been defined
120#ifndef TRAP_HWBKPT
121 #define TRAP_HWBKPT 4
122#endif
123
124// Try to define a macro to encapsulate the tgkill syscall
125// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000126#define tgkill(pid, tid, sig) \
127 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000128
129// We disable the tracing of ptrace calls for integration builds to
130// avoid the additional indirection and checks.
131#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000132#define PTRACE(req, pid, addr, data, data_size, error) \
133 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000134#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000135#define PTRACE(req, pid, addr, data, data_size, error) \
136 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000137#endif
138
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000139using namespace lldb;
140using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000141using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000142using namespace llvm;
143
Todd Fialaaf245d12014-06-30 21:05:18 +0000144// Private bits we only need internally.
145namespace
146{
Tamas Berghammer43f2d972015-03-04 11:10:03 +0000147 static void * const EXIT_OPERATION = nullptr;
148
Todd Fialaaf245d12014-06-30 21:05:18 +0000149 const UnixSignals&
150 GetUnixSignals ()
151 {
152 static process_linux::LinuxSignals signals;
153 return signals;
154 }
155
Chaoren Linfa03ad22015-02-03 01:50:42 +0000156 ThreadStateCoordinator::LogFunction
157 GetThreadLoggerFunction ()
158 {
159 return [](const char *format, va_list args)
160 {
161 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
162 if (log)
163 log->VAPrintf (format, args);
164 };
165 }
166
167 void
168 CoordinatorErrorHandler (const std::string &error_message)
169 {
170 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
171 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000172 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000173 assert (false && "ThreadStateCoordinator error reported");
174 }
175
Todd Fialaaf245d12014-06-30 21:05:18 +0000176 Error
177 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
178 {
179 // Grab process info for the running process.
180 ProcessInstanceInfo process_info;
181 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000182 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000183
184 // Resolve the executable module.
185 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000186 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000187 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
188 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000189 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000190 exe_module_sp,
191 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
192
193 if (!error.Success ())
194 return error;
195
196 // Check if we've got our architecture from the exe_module.
197 arch = exe_module_sp->GetArchitecture ();
198 if (arch.IsValid ())
199 return Error();
200 else
201 return Error("failed to retrieve a valid architecture from the exe module");
202 }
203
204 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000205 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000206 {
207 uint8_t *ptr = (uint8_t *)bytes;
208 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
209 for(uint32_t i=0; i<loop_count; i++)
210 {
211 s.Printf ("[%x]", *ptr);
212 ptr++;
213 }
214 }
215
216 void
217 PtraceDisplayBytes(int &req, void *data, size_t data_size)
218 {
219 StreamString buf;
220 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
221 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
222
223 if (verbose_log)
224 {
225 switch(req)
226 {
227 case PTRACE_POKETEXT:
228 {
229 DisplayBytes(buf, &data, 8);
230 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
231 break;
232 }
233 case PTRACE_POKEDATA:
234 {
235 DisplayBytes(buf, &data, 8);
236 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
237 break;
238 }
239 case PTRACE_POKEUSER:
240 {
241 DisplayBytes(buf, &data, 8);
242 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
243 break;
244 }
245 case PTRACE_SETREGS:
246 {
247 DisplayBytes(buf, data, data_size);
248 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
249 break;
250 }
251 case PTRACE_SETFPREGS:
252 {
253 DisplayBytes(buf, data, data_size);
254 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
255 break;
256 }
257 case PTRACE_SETSIGINFO:
258 {
259 DisplayBytes(buf, data, sizeof(siginfo_t));
260 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
261 break;
262 }
263 case PTRACE_SETREGSET:
264 {
265 // Extract iov_base from data, which is a pointer to the struct IOVEC
266 DisplayBytes(buf, *(void **)data, data_size);
267 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
268 break;
269 }
270 default:
271 {
272 }
273 }
274 }
275 }
276
277 // Wrapper for ptrace to catch errors and log calls.
278 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
279 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000280 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
281 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000282 {
283 long int result;
284
285 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
286
287 PtraceDisplayBytes(req, data, data_size);
288
Chaoren Lin97ccc292015-02-03 01:51:12 +0000289 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 errno = 0;
291 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000292 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000293 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000294 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000295
Chaoren Lin97ccc292015-02-03 01:51:12 +0000296 if (result == -1)
297 error.SetErrorToErrno();
298
Todd Fialaaf245d12014-06-30 21:05:18 +0000299 if (log)
300 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
301 reqName, pid, addr, data, data_size, result, file, line);
302
303 PtraceDisplayBytes(req, data, data_size);
304
Chaoren Lin97ccc292015-02-03 01:51:12 +0000305 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 {
307 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000308 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000309 {
310 case ESRCH: str = "ESRCH"; break;
311 case EINVAL: str = "EINVAL"; break;
312 case EBUSY: str = "EBUSY"; break;
313 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000314 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000315 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000316 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000317 }
318
319 return result;
320 }
321
322#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
323 // Wrapper for ptrace when logging is not required.
324 // Sets errno to 0 prior to calling ptrace.
325 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000326 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000327 {
328 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000329
330 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 errno = 0;
332 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000333 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000335 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000336
337 if (result == -1)
338 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000339 return result;
340 }
341#endif
342
343 //------------------------------------------------------------------------------
344 // Static implementations of NativeProcessLinux::ReadMemory and
345 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
346 // functions without needed to go thru the thread funnel.
347
Chaoren Lin97ccc292015-02-03 01:51:12 +0000348 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000349 DoReadMemory (
350 lldb::pid_t pid,
351 lldb::addr_t vm_addr,
352 void *buf,
353 lldb::addr_t size,
354 Error &error)
355 {
356 // ptrace word size is determined by the host, not the child
357 static const unsigned word_size = sizeof(void*);
358 unsigned char *dst = static_cast<unsigned char*>(buf);
359 lldb::addr_t bytes_read;
360 lldb::addr_t remainder;
361 long data;
362
363 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
364 if (log)
365 ProcessPOSIXLog::IncNestLevel();
366 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
367 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
368 pid, word_size, (void*)vm_addr, buf, size);
369
370 assert(sizeof(data) >= word_size);
371 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
372 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000373 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
374 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000376 if (log)
377 ProcessPOSIXLog::DecNestLevel();
378 return bytes_read;
379 }
380
381 remainder = size - bytes_read;
382 remainder = remainder > word_size ? word_size : remainder;
383
384 // Copy the data into our buffer
385 for (unsigned i = 0; i < remainder; ++i)
386 dst[i] = ((data >> i*8) & 0xFF);
387
388 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
389 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
390 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
391 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
392 {
393 uintptr_t print_dst = 0;
394 // Format bytes from data by moving into print_dst for log output
395 for (unsigned i = 0; i < remainder; ++i)
396 print_dst |= (((data >> i*8) & 0xFF) << i*8);
397 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
398 (void*)vm_addr, print_dst, (unsigned long)data);
399 }
400
401 vm_addr += word_size;
402 dst += word_size;
403 }
404
405 if (log)
406 ProcessPOSIXLog::DecNestLevel();
407 return bytes_read;
408 }
409
Chaoren Lin97ccc292015-02-03 01:51:12 +0000410 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000411 DoWriteMemory(
412 lldb::pid_t pid,
413 lldb::addr_t vm_addr,
414 const void *buf,
415 lldb::addr_t size,
416 Error &error)
417 {
418 // ptrace word size is determined by the host, not the child
419 static const unsigned word_size = sizeof(void*);
420 const unsigned char *src = static_cast<const unsigned char*>(buf);
421 lldb::addr_t bytes_written = 0;
422 lldb::addr_t remainder;
423
424 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
425 if (log)
426 ProcessPOSIXLog::IncNestLevel();
427 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
428 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
429 pid, word_size, (void*)vm_addr, buf, size);
430
431 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
432 {
433 remainder = size - bytes_written;
434 remainder = remainder > word_size ? word_size : remainder;
435
436 if (remainder == word_size)
437 {
438 unsigned long data = 0;
439 assert(sizeof(data) >= word_size);
440 for (unsigned i = 0; i < word_size; ++i)
441 data |= (unsigned long)src[i] << i*8;
442
443 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
446 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
447 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000448 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000449
Chaoren Lin97ccc292015-02-03 01:51:12 +0000450 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000451 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 if (log)
453 ProcessPOSIXLog::DecNestLevel();
454 return bytes_written;
455 }
456 }
457 else
458 {
459 unsigned char buff[8];
460 if (DoReadMemory(pid, vm_addr,
461 buff, word_size, error) != word_size)
462 {
463 if (log)
464 ProcessPOSIXLog::DecNestLevel();
465 return bytes_written;
466 }
467
468 memcpy(buff, src, remainder);
469
470 if (DoWriteMemory(pid, vm_addr,
471 buff, word_size, error) != word_size)
472 {
473 if (log)
474 ProcessPOSIXLog::DecNestLevel();
475 return bytes_written;
476 }
477
478 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
479 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
480 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
481 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
482 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000483 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 }
485
486 vm_addr += word_size;
487 src += word_size;
488 }
489 if (log)
490 ProcessPOSIXLog::DecNestLevel();
491 return bytes_written;
492 }
493
494 //------------------------------------------------------------------------------
495 /// @class Operation
496 /// @brief Represents a NativeProcessLinux operation.
497 ///
498 /// Under Linux, it is not possible to ptrace() from any other thread but the
499 /// one that spawned or attached to the process from the start. Therefore, when
500 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
501 /// process the operation must be "funneled" to a specific thread to perform the
502 /// task. The Operation class provides an abstract base for all services the
503 /// NativeProcessLinux must perform via the single virtual function Execute, thus
504 /// encapsulating the code that needs to run in the privileged context.
505 class Operation
506 {
507 public:
508 Operation () : m_error() { }
509
510 virtual
511 ~Operation() {}
512
513 virtual void
514 Execute (NativeProcessLinux *process) = 0;
515
516 const Error &
517 GetError () const { return m_error; }
518
519 protected:
520 Error m_error;
521 };
522
523 //------------------------------------------------------------------------------
524 /// @class ReadOperation
525 /// @brief Implements NativeProcessLinux::ReadMemory.
526 class ReadOperation : public Operation
527 {
528 public:
529 ReadOperation (
530 lldb::addr_t addr,
531 void *buff,
532 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000533 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000534 Operation (),
535 m_addr (addr),
536 m_buff (buff),
537 m_size (size),
538 m_result (result)
539 {
540 }
541
542 void Execute (NativeProcessLinux *process) override;
543
544 private:
545 lldb::addr_t m_addr;
546 void *m_buff;
547 lldb::addr_t m_size;
548 lldb::addr_t &m_result;
549 };
550
551 void
552 ReadOperation::Execute (NativeProcessLinux *process)
553 {
554 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
555 }
556
557 //------------------------------------------------------------------------------
558 /// @class WriteOperation
559 /// @brief Implements NativeProcessLinux::WriteMemory.
560 class WriteOperation : public Operation
561 {
562 public:
563 WriteOperation (
564 lldb::addr_t addr,
565 const void *buff,
566 lldb::addr_t size,
567 lldb::addr_t &result) :
568 Operation (),
569 m_addr (addr),
570 m_buff (buff),
571 m_size (size),
572 m_result (result)
573 {
574 }
575
576 void Execute (NativeProcessLinux *process) override;
577
578 private:
579 lldb::addr_t m_addr;
580 const void *m_buff;
581 lldb::addr_t m_size;
582 lldb::addr_t &m_result;
583 };
584
585 void
586 WriteOperation::Execute(NativeProcessLinux *process)
587 {
588 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
589 }
590
591 //------------------------------------------------------------------------------
592 /// @class ReadRegOperation
593 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
594 class ReadRegOperation : public Operation
595 {
596 public:
597 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000598 RegisterValue &value)
599 : m_tid(tid),
600 m_offset(static_cast<uintptr_t> (offset)),
601 m_reg_name(reg_name),
602 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000603 { }
604
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000605 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000606
607 private:
608 lldb::tid_t m_tid;
609 uintptr_t m_offset;
610 const char *m_reg_name;
611 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 };
613
614 void
615 ReadRegOperation::Execute(NativeProcessLinux *monitor)
616 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000617#if defined (__arm64__) || defined (__aarch64__)
618 if (m_offset > sizeof(struct user_pt_regs))
619 {
620 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
621 if (offset > sizeof(struct user_fpsimd_state))
622 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000623 m_error.SetErrorString("invalid offset value");
624 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000625 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000626 elf_fpregset_t regs;
627 int regset = NT_FPREGSET;
628 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000629
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 ioVec.iov_base = &regs;
631 ioVec.iov_len = sizeof regs;
632 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
633 if (m_error.Success())
634 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000635 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000636 if (monitor->GetArchitecture(arch))
637 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000638 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000639 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000640 }
641 }
642 else
643 {
644 elf_gregset_t regs;
645 int regset = NT_PRSTATUS;
646 struct iovec ioVec;
647
648 ioVec.iov_base = &regs;
649 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000650 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
651 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000652 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000653 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000654 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000656 else
657 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000658 }
659 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000660#elif defined (__mips__)
661 elf_gregset_t regs;
662 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
663 if (m_error.Success())
664 {
665 lldb_private::ArchSpec arch;
666 if (monitor->GetArchitecture(arch))
667 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
668 else
669 m_error.SetErrorString("failed to get architecture");
670 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000671#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000672 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
673
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000674 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 +0000675 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000677
Todd Fialaaf245d12014-06-30 21:05:18 +0000678 if (log)
679 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
680 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000681#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 }
683
684 //------------------------------------------------------------------------------
685 /// @class WriteRegOperation
686 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
687 class WriteRegOperation : public Operation
688 {
689 public:
690 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000691 const RegisterValue &value)
692 : m_tid(tid),
693 m_offset(offset),
694 m_reg_name(reg_name),
695 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000696 { }
697
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000698 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000699
700 private:
701 lldb::tid_t m_tid;
702 uintptr_t m_offset;
703 const char *m_reg_name;
704 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000705 };
706
707 void
708 WriteRegOperation::Execute(NativeProcessLinux *monitor)
709 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000710#if defined (__arm64__) || defined (__aarch64__)
711 if (m_offset > sizeof(struct user_pt_regs))
712 {
713 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
714 if (offset > sizeof(struct user_fpsimd_state))
715 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000716 m_error.SetErrorString("invalid offset value");
717 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000718 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000719 elf_fpregset_t regs;
720 int regset = NT_FPREGSET;
721 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000722
Chaoren Lin97ccc292015-02-03 01:51:12 +0000723 ioVec.iov_base = &regs;
724 ioVec.iov_len = sizeof regs;
725 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000726 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000727 {
728 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
729 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000730 }
731 }
732 else
733 {
734 elf_gregset_t regs;
735 int regset = NT_PRSTATUS;
736 struct iovec ioVec;
737
738 ioVec.iov_base = &regs;
739 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000740 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000741 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000742 {
743 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000744 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000745 }
746 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000747#elif defined (__mips__)
748 elf_gregset_t regs;
749 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
750 if (m_error.Success())
751 {
752 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
753 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
754 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000755#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 void* buf;
757 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
758
759 buf = (void*) m_value.GetAsUInt64();
760
761 if (log)
762 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000763 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000764#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000765 }
766
767 //------------------------------------------------------------------------------
768 /// @class ReadGPROperation
769 /// @brief Implements NativeProcessLinux::ReadGPR.
770 class ReadGPROperation : public Operation
771 {
772 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000773 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
774 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000775 { }
776
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000777 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000778
779 private:
780 lldb::tid_t m_tid;
781 void *m_buf;
782 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000783 };
784
785 void
786 ReadGPROperation::Execute(NativeProcessLinux *monitor)
787 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000788#if defined (__arm64__) || defined (__aarch64__)
789 int regset = NT_PRSTATUS;
790 struct iovec ioVec;
791
792 ioVec.iov_base = m_buf;
793 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000794 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000795#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000796 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000797#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 }
799
800 //------------------------------------------------------------------------------
801 /// @class ReadFPROperation
802 /// @brief Implements NativeProcessLinux::ReadFPR.
803 class ReadFPROperation : public Operation
804 {
805 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000806 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
807 : m_tid(tid),
808 m_buf(buf),
809 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000810 { }
811
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000812 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000813
814 private:
815 lldb::tid_t m_tid;
816 void *m_buf;
817 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 };
819
820 void
821 ReadFPROperation::Execute(NativeProcessLinux *monitor)
822 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000823#if defined (__arm64__) || defined (__aarch64__)
824 int regset = NT_FPREGSET;
825 struct iovec ioVec;
826
827 ioVec.iov_base = m_buf;
828 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000829 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000830#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000831 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000832#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 }
834
835 //------------------------------------------------------------------------------
836 /// @class ReadRegisterSetOperation
837 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
838 class ReadRegisterSetOperation : public Operation
839 {
840 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000841 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
842 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000843 { }
844
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000845 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000846
847 private:
848 lldb::tid_t m_tid;
849 void *m_buf;
850 size_t m_buf_size;
851 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000852 };
853
854 void
855 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
856 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000857 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000858 }
859
860 //------------------------------------------------------------------------------
861 /// @class WriteGPROperation
862 /// @brief Implements NativeProcessLinux::WriteGPR.
863 class WriteGPROperation : public Operation
864 {
865 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000866 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
867 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000868 { }
869
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000870 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000871
872 private:
873 lldb::tid_t m_tid;
874 void *m_buf;
875 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000876 };
877
878 void
879 WriteGPROperation::Execute(NativeProcessLinux *monitor)
880 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000881#if defined (__arm64__) || defined (__aarch64__)
882 int regset = NT_PRSTATUS;
883 struct iovec ioVec;
884
885 ioVec.iov_base = m_buf;
886 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000887 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000888#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000889 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000890#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000891 }
892
893 //------------------------------------------------------------------------------
894 /// @class WriteFPROperation
895 /// @brief Implements NativeProcessLinux::WriteFPR.
896 class WriteFPROperation : public Operation
897 {
898 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000899 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
900 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000901 { }
902
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000903 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000904
905 private:
906 lldb::tid_t m_tid;
907 void *m_buf;
908 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000909 };
910
911 void
912 WriteFPROperation::Execute(NativeProcessLinux *monitor)
913 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000914#if defined (__arm64__) || defined (__aarch64__)
915 int regset = NT_FPREGSET;
916 struct iovec ioVec;
917
918 ioVec.iov_base = m_buf;
919 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000920 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000921#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000922 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000923#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 }
925
926 //------------------------------------------------------------------------------
927 /// @class WriteRegisterSetOperation
928 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
929 class WriteRegisterSetOperation : public Operation
930 {
931 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000932 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
933 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000934 { }
935
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000936 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000937
938 private:
939 lldb::tid_t m_tid;
940 void *m_buf;
941 size_t m_buf_size;
942 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000943 };
944
945 void
946 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
947 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000948 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000949 }
950
951 //------------------------------------------------------------------------------
952 /// @class ResumeOperation
953 /// @brief Implements NativeProcessLinux::Resume.
954 class ResumeOperation : public Operation
955 {
956 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000957 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
958 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000959
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000960 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000961
962 private:
963 lldb::tid_t m_tid;
964 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000965 };
966
967 void
968 ResumeOperation::Execute(NativeProcessLinux *monitor)
969 {
970 intptr_t data = 0;
971
972 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
973 data = m_signo;
974
Chaoren Lin97ccc292015-02-03 01:51:12 +0000975 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
976 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000977 {
978 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
979
980 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000981 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000982 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000983 }
984
985 //------------------------------------------------------------------------------
986 /// @class SingleStepOperation
987 /// @brief Implements NativeProcessLinux::SingleStep.
988 class SingleStepOperation : public Operation
989 {
990 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000991 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
992 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000993
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000994 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000995
996 private:
997 lldb::tid_t m_tid;
998 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000999 };
1000
1001 void
1002 SingleStepOperation::Execute(NativeProcessLinux *monitor)
1003 {
1004 intptr_t data = 0;
1005
1006 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1007 data = m_signo;
1008
Chaoren Lin97ccc292015-02-03 01:51:12 +00001009 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001010 }
1011
1012 //------------------------------------------------------------------------------
1013 /// @class SiginfoOperation
1014 /// @brief Implements NativeProcessLinux::GetSignalInfo.
1015 class SiginfoOperation : public Operation
1016 {
1017 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001018 SiginfoOperation(lldb::tid_t tid, void *info)
1019 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001020
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001021 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001022
1023 private:
1024 lldb::tid_t m_tid;
1025 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001026 };
1027
1028 void
1029 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1030 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001031 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 }
1033
1034 //------------------------------------------------------------------------------
1035 /// @class EventMessageOperation
1036 /// @brief Implements NativeProcessLinux::GetEventMessage.
1037 class EventMessageOperation : public Operation
1038 {
1039 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001040 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1041 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001042
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001043 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001044
1045 private:
1046 lldb::tid_t m_tid;
1047 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001048 };
1049
1050 void
1051 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1052 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001053 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001054 }
1055
1056 class DetachOperation : public Operation
1057 {
1058 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001059 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001060
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001061 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001062
1063 private:
1064 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001065 };
1066
1067 void
1068 DetachOperation::Execute(NativeProcessLinux *monitor)
1069 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001070 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001071 }
1072
1073}
1074
Todd Fialaaf245d12014-06-30 21:05:18 +00001075// Simple helper function to ensure flags are enabled on the given file
1076// descriptor.
1077static bool
1078EnsureFDFlags(int fd, int flags, Error &error)
1079{
1080 int status;
1081
1082 if ((status = fcntl(fd, F_GETFL)) == -1)
1083 {
1084 error.SetErrorToErrno();
1085 return false;
1086 }
1087
1088 if (fcntl(fd, F_SETFL, status | flags) == -1)
1089 {
1090 error.SetErrorToErrno();
1091 return false;
1092 }
1093
1094 return true;
1095}
1096
1097NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1098 : m_monitor(monitor)
1099{
1100 sem_init(&m_semaphore, 0, 0);
1101}
1102
1103NativeProcessLinux::OperationArgs::~OperationArgs()
1104{
1105 sem_destroy(&m_semaphore);
1106}
1107
1108NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001109 Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001110 char const **argv,
1111 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001112 const std::string &stdin_path,
1113 const std::string &stdout_path,
1114 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001115 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001116 const ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001117 : OperationArgs(monitor),
1118 m_module(module),
1119 m_argv(argv),
1120 m_envp(envp),
1121 m_stdin_path(stdin_path),
1122 m_stdout_path(stdout_path),
1123 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001124 m_working_dir(working_dir),
1125 m_launch_info(launch_info)
1126{
1127}
Todd Fialaaf245d12014-06-30 21:05:18 +00001128
1129NativeProcessLinux::LaunchArgs::~LaunchArgs()
1130{ }
1131
1132NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1133 lldb::pid_t pid)
1134 : OperationArgs(monitor), m_pid(pid) { }
1135
1136NativeProcessLinux::AttachArgs::~AttachArgs()
1137{ }
1138
1139// -----------------------------------------------------------------------------
1140// Public Static Methods
1141// -----------------------------------------------------------------------------
1142
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001143Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001144NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001145 Module *exe_module,
1146 ProcessLaunchInfo &launch_info,
1147 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001148 NativeProcessProtocolSP &native_process_sp)
1149{
1150 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1151
1152 Error error;
1153
1154 // Verify the working directory is valid if one was specified.
1155 const char* working_dir = launch_info.GetWorkingDirectory ();
1156 if (working_dir)
1157 {
1158 FileSpec working_dir_fs (working_dir, true);
1159 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1160 {
1161 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1162 return error;
1163 }
1164 }
1165
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001166 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001167
1168 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001169 std::string stdin_path;
1170 std::string stdout_path;
1171 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001172
1173 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001174 if (file_action)
1175 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001176
1177 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001178 if (file_action)
1179 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001180
1181 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001182 if (file_action)
1183 stderr_path = file_action->GetPath ();
1184
1185 if (log)
1186 {
1187 if (!stdin_path.empty ())
1188 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1189 else
1190 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1191
1192 if (!stdout_path.empty ())
1193 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1194 else
1195 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1196
1197 if (!stderr_path.empty ())
1198 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1199 else
1200 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1201 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001202
1203 // Create the NativeProcessLinux in launch mode.
1204 native_process_sp.reset (new NativeProcessLinux ());
1205
1206 if (log)
1207 {
1208 int i = 0;
1209 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1210 {
1211 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1212 ++i;
1213 }
1214 }
1215
1216 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1217 {
1218 native_process_sp.reset ();
1219 error.SetErrorStringWithFormat ("failed to register the native delegate");
1220 return error;
1221 }
1222
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001223 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001224 exe_module,
1225 launch_info.GetArguments ().GetConstArgumentVector (),
1226 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1227 stdin_path,
1228 stdout_path,
1229 stderr_path,
1230 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001231 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 error);
1233
1234 if (error.Fail ())
1235 {
1236 native_process_sp.reset ();
1237 if (log)
1238 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1239 return error;
1240 }
1241
1242 launch_info.SetProcessID (native_process_sp->GetID ());
1243
1244 return error;
1245}
1246
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001247Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001248NativeProcessLinux::AttachToProcess (
1249 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001250 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001251 NativeProcessProtocolSP &native_process_sp)
1252{
1253 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1254 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1255 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1256
1257 // Grab the current platform architecture. This should be Linux,
1258 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001259 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001260 if (!platform_sp)
1261 return Error("failed to get a valid default platform");
1262
1263 // Retrieve the architecture for the running process.
1264 ArchSpec process_arch;
1265 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1266 if (!error.Success ())
1267 return error;
1268
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001269 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001270
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001271 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001272 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001273 error.SetErrorStringWithFormat ("failed to register the native delegate");
1274 return error;
1275 }
1276
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001277 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001278 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001279 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001280
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001281 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001282 return error;
1283}
1284
1285// -----------------------------------------------------------------------------
1286// Public Instance Methods
1287// -----------------------------------------------------------------------------
1288
1289NativeProcessLinux::NativeProcessLinux () :
1290 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1291 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001292 m_operation_thread (),
1293 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001294 m_operation (nullptr),
1295 m_operation_mutex (),
1296 m_operation_pending (),
1297 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001298 m_supports_mem_region (eLazyBoolCalculate),
1299 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001300 m_mem_region_cache_mutex (),
1301 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1302 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001303{
1304}
1305
1306//------------------------------------------------------------------------------
1307/// The basic design of the NativeProcessLinux is built around two threads.
1308///
1309/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1310/// for changes in the debugee state. When a change is detected a
1311/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1312/// "drives" state changes in the debugger.
1313///
1314/// The second thread (@see OperationThread) is responsible for two things 1)
1315/// launching or attaching to the inferior process, and then 2) servicing
1316/// operations such as register reads/writes, stepping, etc. See the comments
1317/// on the Operation class for more info as to why this is needed.
1318void
1319NativeProcessLinux::LaunchInferior (
1320 Module *module,
1321 const char *argv[],
1322 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001323 const std::string &stdin_path,
1324 const std::string &stdout_path,
1325 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001326 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001327 const ProcessLaunchInfo &launch_info,
1328 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001329{
1330 if (module)
1331 m_arch = module->GetArchitecture ();
1332
Chaoren Linfa03ad22015-02-03 01:50:42 +00001333 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001334
1335 std::unique_ptr<LaunchArgs> args(
1336 new LaunchArgs(
1337 this, module, argv, envp,
1338 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001339 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001340
Chaoren Linfa03ad22015-02-03 01:50:42 +00001341 sem_init (&m_operation_pending, 0, 0);
1342 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001343
Chaoren Linfa03ad22015-02-03 01:50:42 +00001344 StartLaunchOpThread (args.get(), error);
1345 if (!error.Success ())
1346 return;
1347
1348 error = StartCoordinatorThread ();
1349 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001350 return;
1351
1352WAIT_AGAIN:
1353 // Wait for the operation thread to initialize.
1354 if (sem_wait(&args->m_semaphore))
1355 {
1356 if (errno == EINTR)
1357 goto WAIT_AGAIN;
1358 else
1359 {
1360 error.SetErrorToErrno();
1361 return;
1362 }
1363 }
1364
1365 // Check that the launch was a success.
1366 if (!args->m_error.Success())
1367 {
1368 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001369 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001370 error = args->m_error;
1371 return;
1372 }
1373
1374 // Finally, start monitoring the child process for change in state.
1375 m_monitor_thread = Host::StartMonitoringChildProcess(
1376 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001377 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001378 {
1379 error.SetErrorToGenericError();
1380 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1381 return;
1382 }
1383}
1384
1385void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001386NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001387{
1388 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1389 if (log)
1390 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1391
1392 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001393 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001394 if (!platform_sp)
1395 {
1396 if (log)
1397 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1398 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001399 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001400 }
1401
1402 // Gather info about the process.
1403 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001404 if (!platform_sp->GetProcessInfo (pid, process_info))
1405 {
1406 if (log)
1407 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1408 error.SetErrorString ("failed to get process info");
1409 return;
1410 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001411
1412 // Resolve the executable module
1413 ModuleSP exe_module_sp;
1414 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001415 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001416 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001417 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001418 if (!error.Success())
1419 return;
1420
1421 // Set the architecture to the exe architecture.
1422 m_arch = exe_module_sp->GetArchitecture();
1423 if (log)
1424 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1425
1426 m_pid = pid;
1427 SetState(eStateAttaching);
1428
1429 sem_init (&m_operation_pending, 0, 0);
1430 sem_init (&m_operation_done, 0, 0);
1431
1432 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1433
1434 StartAttachOpThread(args.get (), error);
1435 if (!error.Success ())
1436 return;
1437
Chaoren Linfa03ad22015-02-03 01:50:42 +00001438 error = StartCoordinatorThread ();
1439 if (!error.Success ())
1440 return;
1441
Todd Fialaaf245d12014-06-30 21:05:18 +00001442WAIT_AGAIN:
1443 // Wait for the operation thread to initialize.
1444 if (sem_wait (&args->m_semaphore))
1445 {
1446 if (errno == EINTR)
1447 goto WAIT_AGAIN;
1448 else
1449 {
1450 error.SetErrorToErrno ();
1451 return;
1452 }
1453 }
1454
1455 // Check that the attach was a success.
1456 if (!args->m_error.Success ())
1457 {
1458 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001459 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001460 error = args->m_error;
1461 return;
1462 }
1463
1464 // Finally, start monitoring the child process for change in state.
1465 m_monitor_thread = Host::StartMonitoringChildProcess (
1466 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001467 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001468 {
1469 error.SetErrorToGenericError ();
1470 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1471 return;
1472 }
1473}
1474
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001475void
1476NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001477{
1478 StopMonitor();
1479}
1480
1481//------------------------------------------------------------------------------
1482// Thread setup and tear down.
1483
1484void
1485NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1486{
1487 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1488
Zachary Turneracee96a2014-09-23 18:32:09 +00001489 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001490 return;
1491
Zachary Turner39de3112014-09-09 20:54:56 +00001492 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001493}
1494
1495void *
1496NativeProcessLinux::LaunchOpThread(void *arg)
1497{
1498 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1499
1500 if (!Launch(args)) {
1501 sem_post(&args->m_semaphore);
1502 return NULL;
1503 }
1504
1505 ServeOperation(args);
1506 return NULL;
1507}
1508
1509bool
1510NativeProcessLinux::Launch(LaunchArgs *args)
1511{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001512 assert (args && "null args");
1513 if (!args)
1514 return false;
1515
Todd Fialaaf245d12014-06-30 21:05:18 +00001516 NativeProcessLinux *monitor = args->m_monitor;
1517 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001518
1519 const char **argv = args->m_argv;
1520 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001521 const char *working_dir = args->m_working_dir;
1522
1523 lldb_utility::PseudoTerminal terminal;
1524 const size_t err_len = 1024;
1525 char err_str[err_len];
1526 lldb::pid_t pid;
1527 NativeThreadProtocolSP thread_sp;
1528
1529 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001530
1531 // Propagate the environment if one is not supplied.
1532 if (envp == NULL || envp[0] == NULL)
1533 envp = const_cast<const char **>(environ);
1534
1535 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1536 {
1537 args->m_error.SetErrorToGenericError();
1538 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001539 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001540 }
1541
1542 // Recognized child exit status codes.
1543 enum {
1544 ePtraceFailed = 1,
1545 eDupStdinFailed,
1546 eDupStdoutFailed,
1547 eDupStderrFailed,
1548 eChdirFailed,
1549 eExecFailed,
1550 eSetGidFailed
1551 };
1552
1553 // Child process.
1554 if (pid == 0)
1555 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001556 // FIXME consider opening a pipe between parent/child and have this forked child
1557 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001558
Todd Fiala75f47c32014-10-11 21:42:09 +00001559 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001560 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1561 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001562 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001563
Pavel Labath493c3a12015-02-04 10:36:57 +00001564 // terminal has already dupped the tty descriptors to stdin/out/err.
1565 // This closes original fd from which they were copied (and avoids
1566 // leaking descriptors to the debugged process.
1567 terminal.CloseSlaveFileDescriptor();
1568
Todd Fialaaf245d12014-06-30 21:05:18 +00001569 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001570 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001572
1573 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001574 if (setpgid(0, 0) != 0)
1575 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001576 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 // Don't allow this to prevent an inferior exec.
1578 }
1579
1580 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001581 if (!args->m_stdin_path.empty ())
1582 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001583 exit(eDupStdinFailed);
1584
Todd Fiala75f47c32014-10-11 21:42:09 +00001585 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001586 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001587 exit(eDupStdoutFailed);
1588
Todd Fiala75f47c32014-10-11 21:42:09 +00001589 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001590 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001591 exit(eDupStderrFailed);
1592
1593 // Change working directory
1594 if (working_dir != NULL && working_dir[0])
1595 if (0 != ::chdir(working_dir))
1596 exit(eChdirFailed);
1597
Todd Fiala0bce1b62014-08-17 00:10:50 +00001598 // Disable ASLR if requested.
1599 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1600 {
1601 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1602 if (old_personality == -1)
1603 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001604 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001605 }
1606 else
1607 {
1608 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1609 if (new_personality == -1)
1610 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001611 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001612 }
1613 else
1614 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001615 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001616 }
1617 }
1618 }
1619
Todd Fiala75f47c32014-10-11 21:42:09 +00001620 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001621 execve(argv[0],
1622 const_cast<char *const *>(argv),
1623 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001624
1625 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001626 exit(eExecFailed);
1627 }
1628
Todd Fiala75f47c32014-10-11 21:42:09 +00001629 //
1630 // This is the parent code here.
1631 //
1632 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1633
Todd Fialaaf245d12014-06-30 21:05:18 +00001634 // Wait for the child process to trap on its call to execve.
1635 ::pid_t wpid;
1636 int status;
1637 if ((wpid = waitpid(pid, &status, 0)) < 0)
1638 {
1639 args->m_error.SetErrorToErrno();
1640
1641 if (log)
1642 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1643
1644 // Mark the inferior as invalid.
1645 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1646 monitor->SetState (StateType::eStateInvalid);
1647
Todd Fiala75f47c32014-10-11 21:42:09 +00001648 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001649 }
1650 else if (WIFEXITED(status))
1651 {
1652 // open, dup or execve likely failed for some reason.
1653 args->m_error.SetErrorToGenericError();
1654 switch (WEXITSTATUS(status))
1655 {
1656 case ePtraceFailed:
1657 args->m_error.SetErrorString("Child ptrace failed.");
1658 break;
1659 case eDupStdinFailed:
1660 args->m_error.SetErrorString("Child open stdin failed.");
1661 break;
1662 case eDupStdoutFailed:
1663 args->m_error.SetErrorString("Child open stdout failed.");
1664 break;
1665 case eDupStderrFailed:
1666 args->m_error.SetErrorString("Child open stderr failed.");
1667 break;
1668 case eChdirFailed:
1669 args->m_error.SetErrorString("Child failed to set working directory.");
1670 break;
1671 case eExecFailed:
1672 args->m_error.SetErrorString("Child exec failed.");
1673 break;
1674 case eSetGidFailed:
1675 args->m_error.SetErrorString("Child setgid failed.");
1676 break;
1677 default:
1678 args->m_error.SetErrorString("Child returned unknown exit status.");
1679 break;
1680 }
1681
1682 if (log)
1683 {
1684 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1685 __FUNCTION__,
1686 WEXITSTATUS(status));
1687 }
1688
1689 // Mark the inferior as invalid.
1690 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1691 monitor->SetState (StateType::eStateInvalid);
1692
Todd Fiala75f47c32014-10-11 21:42:09 +00001693 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001695 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001696 "Could not sync with inferior process.");
1697
1698 if (log)
1699 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1700
Chaoren Lin97ccc292015-02-03 01:51:12 +00001701 args->m_error = SetDefaultPtraceOpts(pid);
1702 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001703 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001704 if (log)
1705 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1706 __FUNCTION__,
1707 args->m_error.AsCString ());
1708
1709 // Mark the inferior as invalid.
1710 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1711 monitor->SetState (StateType::eStateInvalid);
1712
Todd Fiala75f47c32014-10-11 21:42:09 +00001713 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001714 }
1715
1716 // Release the master terminal descriptor and pass it off to the
1717 // NativeProcessLinux instance. Similarly stash the inferior pid.
1718 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1719 monitor->m_pid = pid;
1720
1721 // Set the terminal fd to be in non blocking mode (it simplifies the
1722 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1723 // descriptor to read from).
1724 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1725 {
1726 if (log)
1727 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1728 __FUNCTION__,
1729 args->m_error.AsCString ());
1730
1731 // Mark the inferior as invalid.
1732 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1733 monitor->SetState (StateType::eStateInvalid);
1734
Todd Fiala75f47c32014-10-11 21:42:09 +00001735 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001736 }
1737
1738 if (log)
1739 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1740
Chaoren Linfa03ad22015-02-03 01:50:42 +00001741 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001742 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001743 monitor->NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001744 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001745
1746 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001747 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001748 monitor->SetState (StateType::eStateStopped);
1749
Todd Fialaaf245d12014-06-30 21:05:18 +00001750 if (log)
1751 {
1752 if (args->m_error.Success ())
1753 {
1754 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1755 }
1756 else
1757 {
1758 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1759 __FUNCTION__,
1760 args->m_error.AsCString ());
1761 }
1762 }
1763 return args->m_error.Success();
1764}
1765
1766void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001767NativeProcessLinux::StartAttachOpThread(AttachArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001768{
1769 static const char *g_thread_name = "lldb.process.linux.operation";
1770
Zachary Turneracee96a2014-09-23 18:32:09 +00001771 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001772 return;
1773
Zachary Turner39de3112014-09-09 20:54:56 +00001774 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001775}
1776
1777void *
1778NativeProcessLinux::AttachOpThread(void *arg)
1779{
1780 AttachArgs *args = static_cast<AttachArgs*>(arg);
1781
1782 if (!Attach(args)) {
1783 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001784 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001785 }
1786
1787 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001788 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001789}
1790
1791bool
1792NativeProcessLinux::Attach(AttachArgs *args)
1793{
1794 lldb::pid_t pid = args->m_pid;
1795
1796 NativeProcessLinux *monitor = args->m_monitor;
1797 lldb::ThreadSP inferior;
1798 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1799
1800 // Use a map to keep track of the threads which we have attached/need to attach.
1801 Host::TidMap tids_to_attach;
1802 if (pid <= 1)
1803 {
1804 args->m_error.SetErrorToGenericError();
1805 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1806 goto FINISH;
1807 }
1808
1809 while (Host::FindProcessThreads(pid, tids_to_attach))
1810 {
1811 for (Host::TidMap::iterator it = tids_to_attach.begin();
1812 it != tids_to_attach.end();)
1813 {
1814 if (it->second == false)
1815 {
1816 lldb::tid_t tid = it->first;
1817
1818 // Attach to the requested process.
1819 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001820 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1821 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001822 {
1823 // No such thread. The thread may have exited.
1824 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001825 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001826 {
1827 it = tids_to_attach.erase(it);
1828 continue;
1829 }
1830 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001831 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001832 }
1833
1834 int status;
1835 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1836 // At this point we should have a thread stopped if waitpid succeeds.
1837 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1838 {
1839 // No such thread. The thread may have exited.
1840 // More error handling may be needed.
1841 if (errno == ESRCH)
1842 {
1843 it = tids_to_attach.erase(it);
1844 continue;
1845 }
1846 else
1847 {
1848 args->m_error.SetErrorToErrno();
1849 goto FINISH;
1850 }
1851 }
1852
Chaoren Lin97ccc292015-02-03 01:51:12 +00001853 args->m_error = SetDefaultPtraceOpts(tid);
1854 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001855 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001856
1857
1858 if (log)
1859 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1860
1861 it->second = true;
1862
1863 // Create the thread, mark it as stopped.
1864 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1865 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001866
1867 // This will notify this is a new thread and tell the system it is stopped.
1868 monitor->NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001869 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001870 monitor->SetCurrentThreadID (thread_sp->GetID ());
1871 }
1872
1873 // move the loop forward
1874 ++it;
1875 }
1876 }
1877
1878 if (tids_to_attach.size() > 0)
1879 {
1880 monitor->m_pid = pid;
1881 // Let our process instance know the thread has stopped.
1882 monitor->SetState (StateType::eStateStopped);
1883 }
1884 else
1885 {
1886 args->m_error.SetErrorToGenericError();
1887 args->m_error.SetErrorString("No such process.");
1888 }
1889
1890 FINISH:
1891 return args->m_error.Success();
1892}
1893
Chaoren Lin97ccc292015-02-03 01:51:12 +00001894Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001895NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1896{
1897 long ptrace_opts = 0;
1898
1899 // Have the child raise an event on exit. This is used to keep the child in
1900 // limbo until it is destroyed.
1901 ptrace_opts |= PTRACE_O_TRACEEXIT;
1902
1903 // Have the tracer trace threads which spawn in the inferior process.
1904 // TODO: if we want to support tracing the inferiors' child, add the
1905 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1906 ptrace_opts |= PTRACE_O_TRACECLONE;
1907
1908 // Have the tracer notify us before execve returns
1909 // (needed to disable legacy SIGTRAP generation)
1910 ptrace_opts |= PTRACE_O_TRACEEXEC;
1911
Chaoren Lin97ccc292015-02-03 01:51:12 +00001912 Error error;
1913 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1914 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001915}
1916
1917static ExitType convert_pid_status_to_exit_type (int status)
1918{
1919 if (WIFEXITED (status))
1920 return ExitType::eExitTypeExit;
1921 else if (WIFSIGNALED (status))
1922 return ExitType::eExitTypeSignal;
1923 else if (WIFSTOPPED (status))
1924 return ExitType::eExitTypeStop;
1925 else
1926 {
1927 // We don't know what this is.
1928 return ExitType::eExitTypeInvalid;
1929 }
1930}
1931
1932static int convert_pid_status_to_return_code (int status)
1933{
1934 if (WIFEXITED (status))
1935 return WEXITSTATUS (status);
1936 else if (WIFSIGNALED (status))
1937 return WTERMSIG (status);
1938 else if (WIFSTOPPED (status))
1939 return WSTOPSIG (status);
1940 else
1941 {
1942 // We don't know what this is.
1943 return ExitType::eExitTypeInvalid;
1944 }
1945}
1946
1947// Main process monitoring waitpid-loop handler.
1948bool
1949NativeProcessLinux::MonitorCallback(void *callback_baton,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001950 lldb::pid_t pid,
1951 bool exited,
1952 int signal,
1953 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001954{
1955 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1956
1957 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1958 assert (process && "process is null");
1959 if (!process)
1960 {
1961 if (log)
1962 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1963 return true;
1964 }
1965
1966 // Certain activities differ based on whether the pid is the tid of the main thread.
1967 const bool is_main_thread = (pid == process->GetID ());
1968
1969 // Assume we keep monitoring by default.
1970 bool stop_monitoring = false;
1971
1972 // Handle when the thread exits.
1973 if (exited)
1974 {
1975 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001976 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 +00001977
1978 // This is a thread that exited. Ensure we're not tracking it anymore.
1979 const bool thread_found = process->StopTrackingThread (pid);
1980
Chaoren Linfa03ad22015-02-03 01:50:42 +00001981 // Make sure the thread state coordinator knows about this.
1982 process->NotifyThreadDeath (pid);
1983
Todd Fialaaf245d12014-06-30 21:05:18 +00001984 if (is_main_thread)
1985 {
1986 // We only set the exit status and notify the delegate if we haven't already set the process
1987 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1988 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001989 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001990 if (!already_notified)
1991 {
1992 if (log)
1993 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 ()));
1994 // The main thread exited. We're done monitoring. Report to delegate.
1995 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1996
1997 // Notify delegate that our process has exited.
1998 process->SetState (StateType::eStateExited, true);
1999 }
2000 else
2001 {
2002 if (log)
2003 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2004 }
2005 return true;
2006 }
2007 else
2008 {
2009 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2010 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2011 // and we would have done an all-stop then.
2012 if (log)
2013 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2014
2015 // Not the main thread, we keep going.
2016 return false;
2017 }
2018 }
2019
2020 // Get details on the signal raised.
2021 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002022 const auto err = process->GetSignalInfo(pid, &info);
2023 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002024 {
2025 // We have retrieved the signal info. Dispatch appropriately.
2026 if (info.si_signo == SIGTRAP)
2027 process->MonitorSIGTRAP(&info, pid);
2028 else
2029 process->MonitorSignal(&info, pid, exited);
2030
2031 stop_monitoring = false;
2032 }
2033 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002034 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002035 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002036 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002037 // This is a group stop reception for this tid.
2038 if (log)
2039 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2040 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002041 }
2042 else
2043 {
2044 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2045
2046 // A return value of ESRCH means the thread/process is no longer on the system,
2047 // so it was killed somehow outside of our control. Either way, we can't do anything
2048 // with it anymore.
2049
2050 // We stop monitoring if it was the main thread.
2051 stop_monitoring = is_main_thread;
2052
2053 // Stop tracking the metadata for the thread since it's entirely off the system now.
2054 const bool thread_found = process->StopTrackingThread (pid);
2055
Chaoren Linfa03ad22015-02-03 01:50:42 +00002056 // Make sure the thread state coordinator knows about this.
2057 process->NotifyThreadDeath (pid);
2058
Todd Fialaaf245d12014-06-30 21:05:18 +00002059 if (log)
2060 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002061 __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 +00002062
2063 if (is_main_thread)
2064 {
2065 // Notify the delegate - our process is not available but appears to have been killed outside
2066 // our control. Is eStateExited the right exit state in this case?
2067 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2068 process->SetState (StateType::eStateExited, true);
2069 }
2070 else
2071 {
2072 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2073 if (log)
2074 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);
2075 }
2076 }
2077 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002078
2079 return stop_monitoring;
2080}
2081
2082void
2083NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2084{
2085 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2086 const bool is_main_thread = (pid == GetID ());
2087
2088 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2089 if (!info)
2090 return;
2091
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002092 Mutex::Locker locker (m_threads_mutex);
2093
Todd Fialaaf245d12014-06-30 21:05:18 +00002094 // See if we can find a thread for this signal.
2095 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2096 if (!thread_sp)
2097 {
2098 if (log)
2099 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2100 }
2101
2102 switch (info->si_code)
2103 {
2104 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2105 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2106 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2107
2108 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2109 {
2110 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2111
Chaoren Linfa03ad22015-02-03 01:50:42 +00002112 // The main thread is stopped here.
2113 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002114 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002115 NotifyThreadStop (pid);
2116
Todd Fialaaf245d12014-06-30 21:05:18 +00002117 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002118 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002119 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002120 tid = static_cast<lldb::tid_t> (event_message);
2121 if (log)
2122 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002123
Chaoren Linfa03ad22015-02-03 01:50:42 +00002124 // If we don't track the thread yet: create it, mark as stopped.
2125 // If we do track it, this is the wait we needed. Now resume the new thread.
2126 // In all cases, resume the current (i.e. main process) thread.
2127 bool created_now = false;
2128 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2129 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2130
2131 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2132 if (!created_now)
2133 {
2134 // We can now resume the newly created thread since it is fully created.
2135 NotifyThreadCreateStopped (tid);
2136 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002137 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002138 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002139 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002140 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002141 },
2142 CoordinatorErrorHandler);
2143 }
2144 else
2145 {
2146 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2147 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002148 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetLaunching ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002149 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002150 }
2151 else
2152 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002153 if (log)
2154 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 +00002155 }
2156
2157 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002158 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002159 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002160 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002161 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002162 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002163 },
2164 CoordinatorErrorHandler);
2165
Todd Fialaaf245d12014-06-30 21:05:18 +00002166 break;
2167 }
2168
2169 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002170 {
2171 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002172 if (log)
2173 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002174
Chaoren Linfa03ad22015-02-03 01:50:42 +00002175 // The thread state coordinator needs to reset due to the exec.
2176 m_coordinator_up->ResetForExec ();
2177
2178 // 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 +00002179 if (log)
2180 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2181
2182 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002183 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002184 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2185 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002186 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002187 main_thread_sp = thread_sp;
2188 if (log)
2189 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002190 }
2191 else
2192 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002193 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002194 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002195 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002196 }
2197 }
2198
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002199 m_threads.clear ();
2200
2201 if (main_thread_sp)
2202 {
2203 m_threads.push_back (main_thread_sp);
2204 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002205 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002206 }
2207 else
2208 {
2209 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2210 if (log)
2211 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2212 }
2213
Chaoren Linfa03ad22015-02-03 01:50:42 +00002214 // Tell coordinator about about the "new" (since exec) stopped main thread.
2215 const lldb::tid_t main_thread_tid = GetID ();
2216 NotifyThreadCreateStopped (main_thread_tid);
2217
2218 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2219 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002220 // Let our delegate know we have just exec'd.
2221 NotifyDidExec ();
2222
2223 // If we have a main thread, indicate we are stopped.
2224 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002225
2226 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002227 CallAfterRunningThreadsStop (pid,
2228 [=] (lldb::tid_t signaling_tid)
2229 {
2230 SetState (StateType::eStateStopped, true);
2231 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002232
Todd Fialaaf245d12014-06-30 21:05:18 +00002233 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002234 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002235
2236 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2237 {
2238 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002239
2240 // This thread is currently stopped. It's not actually dead yet, just about to be.
2241 NotifyThreadStop (pid);
2242
Todd Fialaaf245d12014-06-30 21:05:18 +00002243 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002244 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002245 data = -1;
2246
2247 if (log)
2248 {
2249 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2250 __FUNCTION__,
2251 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2252 pid,
2253 is_main_thread ? "is main thread" : "not main thread");
2254 }
2255
Todd Fialaaf245d12014-06-30 21:05:18 +00002256 if (is_main_thread)
2257 {
2258 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002259 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002260
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002261 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002262 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002263 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002264 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002265 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002266 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002267 },
2268 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002269
2270 break;
2271 }
2272
2273 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002274 case TRAP_TRACE: // We receive this on single stepping.
2275 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002276 if (thread_sp)
2277 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002278 // If a watchpoint was hit, report it
2279 uint32_t wp_index;
2280 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2281 if (error.Fail() && log)
2282 log->Printf("NativeProcessLinux::%s() "
2283 "received error while checking for watchpoint hits, "
2284 "pid = %" PRIu64 " error = %s",
2285 __FUNCTION__, pid, error.AsCString());
2286 if (wp_index != LLDB_INVALID_INDEX32)
2287 {
2288 MonitorWatchpoint(pid, thread_sp, wp_index);
2289 break;
2290 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002291 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002292 // Otherwise, report step over
2293 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002294 break;
2295
2296 case SI_KERNEL:
2297 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002298 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002299 break;
2300
2301 case SIGTRAP:
2302 case (SIGTRAP | 0x80):
2303 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002304 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2305
2306 // This thread is currently stopped.
2307 NotifyThreadStop (pid);
2308 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002309 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002310
2311
Todd Fialaaf245d12014-06-30 21:05:18 +00002312 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002313 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002314 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002315 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002316 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002317 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002318 },
2319 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002320 break;
2321
2322 default:
2323 assert(false && "Unexpected SIGTRAP code!");
2324 if (log)
2325 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)));
2326 break;
2327
2328 }
2329}
2330
2331void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002332NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2333{
2334 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2335 if (log)
2336 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2337 __FUNCTION__, pid);
2338
2339 if (thread_sp)
2340 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2341
2342 // This thread is currently stopped.
2343 NotifyThreadStop(pid);
2344
2345 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2346 // This would have already happened at the time the Resume() with step operation was signaled.
2347 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2348 // once all running threads have checked in as stopped.
2349 SetCurrentThreadID(pid);
2350 // Tell the process we have a stop (from software breakpoint).
2351 CallAfterRunningThreadsStop(pid,
2352 [=](lldb::tid_t signaling_tid)
2353 {
2354 SetState(StateType::eStateStopped, true);
2355 });
2356}
2357
2358void
2359NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2360{
2361 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2362 if (log)
2363 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2364 __FUNCTION__, pid);
2365
2366 // This thread is currently stopped.
2367 NotifyThreadStop(pid);
2368
2369 // Mark the thread as stopped at breakpoint.
2370 if (thread_sp)
2371 {
2372 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2373 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2374 if (error.Fail())
2375 if (log)
2376 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2377 __FUNCTION__, pid, error.AsCString());
2378 }
2379 else
2380 if (log)
2381 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2382 "warning, cannot process software breakpoint since no thread metadata",
2383 __FUNCTION__, pid);
2384
2385
2386 // We need to tell all other running threads before we notify the delegate about this stop.
2387 CallAfterRunningThreadsStop(pid,
2388 [=](lldb::tid_t deferred_notification_tid)
2389 {
2390 SetCurrentThreadID(deferred_notification_tid);
2391 // Tell the process we have a stop (from software breakpoint).
2392 SetState(StateType::eStateStopped, true);
2393 });
2394}
2395
2396void
2397NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2398{
2399 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2400 if (log)
2401 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2402 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2403 __FUNCTION__, pid, wp_index);
2404
2405 // This thread is currently stopped.
2406 NotifyThreadStop(pid);
2407
2408 // Mark the thread as stopped at watchpoint.
2409 // The address is at (lldb::addr_t)info->si_addr if we need it.
2410 lldbassert(thread_sp && "thread_sp cannot be NULL");
2411 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2412
2413 // We need to tell all other running threads before we notify the delegate about this stop.
2414 CallAfterRunningThreadsStop(pid,
2415 [=](lldb::tid_t deferred_notification_tid)
2416 {
2417 SetCurrentThreadID(deferred_notification_tid);
2418 // Tell the process we have a stop (from watchpoint).
2419 SetState(StateType::eStateStopped, true);
2420 });
2421}
2422
2423void
Todd Fialaaf245d12014-06-30 21:05:18 +00002424NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2425{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002426 assert (info && "null info");
2427 if (!info)
2428 return;
2429
2430 const int signo = info->si_signo;
2431 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002432
2433 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2434
2435 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2436 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2437 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2438 //
2439 // IOW, user generated signals never generate what we consider to be a
2440 // "crash".
2441 //
2442 // Similarly, ACK signals generated by this monitor.
2443
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002444 Mutex::Locker locker (m_threads_mutex);
2445
Todd Fialaaf245d12014-06-30 21:05:18 +00002446 // See if we can find a thread for this signal.
2447 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2448 if (!thread_sp)
2449 {
2450 if (log)
2451 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2452 }
2453
2454 // Handle the signal.
2455 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2456 {
2457 if (log)
2458 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2459 __FUNCTION__,
2460 GetUnixSignals ().GetSignalAsCString (signo),
2461 signo,
2462 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2463 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002464 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002465 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002466 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002467
Todd Fiala58a2f662014-08-12 17:02:07 +00002468 // Check for new thread notification.
2469 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2470 {
2471 // A new thread creation is being signaled. This is one of two parts that come in
2472 // a non-deterministic order. pid is the thread id.
2473 if (log)
2474 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2475 __FUNCTION__, GetID (), pid);
2476
2477 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002478 bool created_now = false;
2479 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002480 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2481
2482 // 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 +00002483 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002484 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002485 // We can now resume the newly created thread since it is fully created.
2486 NotifyThreadCreateStopped (pid);
2487 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002488 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002489 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002490 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002491 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002492 },
2493 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002494 }
2495 else
2496 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002497 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2498 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002499 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002500 }
2501
Todd Fiala58a2f662014-08-12 17:02:07 +00002502 // Done handling.
2503 return;
2504 }
2505
2506 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002507 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002508 {
2509 // This is a tgkill()-based stop.
2510 if (thread_sp)
2511 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002512 if (log)
2513 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2514 __FUNCTION__,
2515 GetID (),
2516 pid);
2517
Chaoren Linaab58632015-02-03 01:50:57 +00002518 // Check that we're not already marked with a stop reason.
2519 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2520 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2521 // and that, without an intervening resume, we received another stop. It is more likely
2522 // that we are missing the marking of a run state somewhere if we find that the thread was
2523 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002524 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2525 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002526
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002527 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002528 if (!StateIsStoppedState (thread_state, false))
2529 {
2530 // An inferior thread just stopped, but was not the primary cause of the process stop.
2531 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2532 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002533 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002534 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002535 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002536 }
2537 else
2538 {
2539 if (log)
2540 {
2541 // Retrieve the signal name if the thread was stopped by a signal.
2542 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002543 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002544 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2545 if (!signal_name)
2546 signal_name = "<no-signal-name>";
2547
2548 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",
2549 __FUNCTION__,
2550 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002551 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002552 StateAsCString (thread_state),
2553 stop_signo,
2554 signal_name);
2555 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002556 // Tell the thread state coordinator about the stop.
2557 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002558 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002559 }
2560
2561 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002562 return;
2563 }
2564
2565 if (log)
2566 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2567
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002568 // This thread is stopped.
2569 NotifyThreadStop (pid);
2570
Todd Fialaaf245d12014-06-30 21:05:18 +00002571 switch (signo)
2572 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002573 case SIGSTOP:
2574 {
2575 if (log)
2576 {
2577 if (is_from_llgs)
2578 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2579 else
2580 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2581 }
2582
Chaoren Linfa03ad22015-02-03 01:50:42 +00002583 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2584 // This thread will get stopped again as part of the group-stop completion.
2585 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002586 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002587 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002588 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002589 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002590 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002591 },
2592 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002593 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002594 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002595 case SIGSEGV:
2596 case SIGILL:
2597 case SIGFPE:
2598 case SIGBUS:
2599 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002600 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002601 break;
2602 default:
2603 // This is just a pre-signal-delivery notification of the incoming signal.
2604 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002605 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002606
2607 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002608 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002609
2610 // Send a stop to the debugger after we get all other threads to stop.
2611 CallAfterRunningThreadsStop (pid,
2612 [=] (lldb::tid_t signaling_tid)
2613 {
2614 SetCurrentThreadID (signaling_tid);
2615 SetState (StateType::eStateStopped, true);
2616 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002617}
2618
2619Error
2620NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2621{
Todd Fialaaf245d12014-06-30 21:05:18 +00002622 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2623 if (log)
2624 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2625
Chaoren Lin03f12d62015-02-03 01:50:49 +00002626 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2627 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002628 int deferred_signo = 0;
2629 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002630 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002631
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002632 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002633
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002634 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002635 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002636 assert (thread_sp && "thread list should not contain NULL threads");
2637
2638 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2639
2640 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002641 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002642 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002643 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2644 __FUNCTION__, GetID (), thread_sp->GetID ());
2645 continue;
2646 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002647
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002648 if (log)
2649 {
2650 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2651 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2652 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002653
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002654 switch (action->state)
2655 {
2656 case eStateRunning:
2657 {
2658 // Run the thread, possibly feeding it the signal.
2659 const int signo = action->signal;
2660 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2661 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2662 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002663 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002664 // Pass this signal number on to the inferior to handle.
2665 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2666 if (resume_result.Success())
2667 SetState(eStateRunning, true);
2668 return resume_result;
2669 },
2670 CoordinatorErrorHandler);
2671 break;
2672 }
2673
2674 case eStateStepping:
2675 {
2676 // Request the step.
2677 const int signo = action->signal;
2678 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2679 [=](lldb::tid_t tid_to_step, bool supress_signal)
2680 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002681 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002682 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2683 assert (step_result.Success() && "SingleStep() failed");
2684 if (step_result.Success())
2685 SetState(eStateStepping, true);
2686 return step_result;
2687 },
2688 CoordinatorErrorHandler);
2689 stepping = true;
2690 break;
2691 }
2692
2693 case eStateSuspended:
2694 case eStateStopped:
2695 // if we haven't chosen a deferred signal tid yet, use this one.
2696 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002697 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002698 deferred_signal_tid = thread_sp->GetID ();
2699 deferred_signal_thread_sp = thread_sp;
2700 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002701 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002702 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002703
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002704 default:
2705 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2706 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002707 }
2708 }
2709
Chaoren Linfa03ad22015-02-03 01:50:42 +00002710 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2711 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002712 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2713 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002714 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002715 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2716 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002717 [=](lldb::tid_t deferred_notification_tid)
2718 {
Chaoren Linae29d392015-02-03 01:50:46 +00002719 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002720 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002721
2722 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002723 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00002724
2725 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002726 SetState (StateType::eStateStopped, true);
2727 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002728 }
2729
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002730 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002731}
2732
2733Error
2734NativeProcessLinux::Halt ()
2735{
2736 Error error;
2737
Todd Fialaaf245d12014-06-30 21:05:18 +00002738 if (kill (GetID (), SIGSTOP) != 0)
2739 error.SetErrorToErrno ();
2740
2741 return error;
2742}
2743
2744Error
2745NativeProcessLinux::Detach ()
2746{
2747 Error error;
2748
2749 // Tell ptrace to detach from the process.
2750 if (GetID () != LLDB_INVALID_PROCESS_ID)
2751 error = Detach (GetID ());
2752
2753 // Stop monitoring the inferior.
2754 StopMonitor ();
2755
2756 // No error.
2757 return error;
2758}
2759
2760Error
2761NativeProcessLinux::Signal (int signo)
2762{
2763 Error error;
2764
2765 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2766 if (log)
2767 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2768 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2769
2770 if (kill(GetID(), signo))
2771 error.SetErrorToErrno();
2772
2773 return error;
2774}
2775
2776Error
Chaoren Line9547b82015-02-03 01:51:00 +00002777NativeProcessLinux::Interrupt ()
2778{
2779 // Pick a running thread (or if none, a not-dead stopped thread) as
2780 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002781 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2782
2783 NativeThreadProtocolSP running_thread_sp;
2784 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002785
2786 if (log)
2787 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2788
2789 Mutex::Locker locker (m_threads_mutex);
2790
2791 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002792 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002793 // The thread shouldn't be null but lets just cover that here.
2794 if (!thread_sp)
2795 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002796
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002797 // If we have a running or stepping thread, we'll call that the
2798 // target of the interrupt.
2799 const auto thread_state = thread_sp->GetState ();
2800 if (thread_state == eStateRunning ||
2801 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002802 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002803 running_thread_sp = thread_sp;
2804 break;
2805 }
2806 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2807 {
2808 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2809 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002810 }
2811 }
2812
2813 if (!running_thread_sp && !stopped_thread_sp)
2814 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002815 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002816 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002817 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002818
Chaoren Line9547b82015-02-03 01:51:00 +00002819 return error;
2820 }
2821
2822 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2823
2824 if (log)
2825 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2826 __FUNCTION__,
2827 GetID (),
2828 running_thread_sp ? "running" : "stopped",
2829 deferred_signal_thread_sp->GetID ());
2830
2831 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2832 [=](lldb::tid_t deferred_notification_tid)
2833 {
2834 // Set the signal thread to the current thread.
2835 SetCurrentThreadID (deferred_notification_tid);
2836
2837 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002838 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00002839
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002840 // Tell the process delegate that the process is in a stopped state.
2841 SetState (StateType::eStateStopped, true);
2842 });
2843 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002844}
2845
2846Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002847NativeProcessLinux::Kill ()
2848{
2849 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2850 if (log)
2851 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2852
2853 Error error;
2854
2855 switch (m_state)
2856 {
2857 case StateType::eStateInvalid:
2858 case StateType::eStateExited:
2859 case StateType::eStateCrashed:
2860 case StateType::eStateDetached:
2861 case StateType::eStateUnloaded:
2862 // Nothing to do - the process is already dead.
2863 if (log)
2864 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2865 return error;
2866
2867 case StateType::eStateConnected:
2868 case StateType::eStateAttaching:
2869 case StateType::eStateLaunching:
2870 case StateType::eStateStopped:
2871 case StateType::eStateRunning:
2872 case StateType::eStateStepping:
2873 case StateType::eStateSuspended:
2874 // We can try to kill a process in these states.
2875 break;
2876 }
2877
2878 if (kill (GetID (), SIGKILL) != 0)
2879 {
2880 error.SetErrorToErrno ();
2881 return error;
2882 }
2883
2884 return error;
2885}
2886
2887static Error
2888ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2889{
2890 memory_region_info.Clear();
2891
2892 StringExtractor line_extractor (maps_line.c_str ());
2893
2894 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2895 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2896
2897 // Parse out the starting address
2898 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2899
2900 // Parse out hyphen separating start and end address from range.
2901 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2902 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2903
2904 // Parse out the ending address
2905 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2906
2907 // Parse out the space after the address.
2908 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2909 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2910
2911 // Save the range.
2912 memory_region_info.GetRange ().SetRangeBase (start_address);
2913 memory_region_info.GetRange ().SetRangeEnd (end_address);
2914
2915 // Parse out each permission entry.
2916 if (line_extractor.GetBytesLeft () < 4)
2917 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2918
2919 // Handle read permission.
2920 const char read_perm_char = line_extractor.GetChar ();
2921 if (read_perm_char == 'r')
2922 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2923 else
2924 {
2925 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2926 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2927 }
2928
2929 // Handle write permission.
2930 const char write_perm_char = line_extractor.GetChar ();
2931 if (write_perm_char == 'w')
2932 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2933 else
2934 {
2935 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2936 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2937 }
2938
2939 // Handle execute permission.
2940 const char exec_perm_char = line_extractor.GetChar ();
2941 if (exec_perm_char == 'x')
2942 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2943 else
2944 {
2945 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2946 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2947 }
2948
2949 return Error ();
2950}
2951
2952Error
2953NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2954{
2955 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2956 // with no perms if it is not mapped.
2957
2958 // Use an approach that reads memory regions from /proc/{pid}/maps.
2959 // Assume proc maps entries are in ascending order.
2960 // FIXME assert if we find differently.
2961 Mutex::Locker locker (m_mem_region_cache_mutex);
2962
2963 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2964 Error error;
2965
2966 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2967 {
2968 // We're done.
2969 error.SetErrorString ("unsupported");
2970 return error;
2971 }
2972
2973 // If our cache is empty, pull the latest. There should always be at least one memory region
2974 // if memory region handling is supported.
2975 if (m_mem_region_cache.empty ())
2976 {
2977 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2978 [&] (const std::string &line) -> bool
2979 {
2980 MemoryRegionInfo info;
2981 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2982 if (parse_error.Success ())
2983 {
2984 m_mem_region_cache.push_back (info);
2985 return true;
2986 }
2987 else
2988 {
2989 if (log)
2990 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2991 return false;
2992 }
2993 });
2994
2995 // If we had an error, we'll mark unsupported.
2996 if (error.Fail ())
2997 {
2998 m_supports_mem_region = LazyBool::eLazyBoolNo;
2999 return error;
3000 }
3001 else if (m_mem_region_cache.empty ())
3002 {
3003 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3004 // is supported. Assume we don't support map entries via procfs.
3005 if (log)
3006 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3007 m_supports_mem_region = LazyBool::eLazyBoolNo;
3008 error.SetErrorString ("not supported");
3009 return error;
3010 }
3011
3012 if (log)
3013 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3014
3015 // We support memory retrieval, remember that.
3016 m_supports_mem_region = LazyBool::eLazyBoolYes;
3017 }
3018 else
3019 {
3020 if (log)
3021 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3022 }
3023
3024 lldb::addr_t prev_base_address = 0;
3025
3026 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3027 // There can be a ton of regions on pthreads apps with lots of threads.
3028 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3029 {
3030 MemoryRegionInfo &proc_entry_info = *it;
3031
3032 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3033 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3034 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3035
3036 // If the target address comes before this entry, indicate distance to next region.
3037 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3038 {
3039 range_info.GetRange ().SetRangeBase (load_addr);
3040 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3041 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3042 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3043 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3044
3045 return error;
3046 }
3047 else if (proc_entry_info.GetRange ().Contains (load_addr))
3048 {
3049 // The target address is within the memory region we're processing here.
3050 range_info = proc_entry_info;
3051 return error;
3052 }
3053
3054 // The target memory address comes somewhere after the region we just parsed.
3055 }
3056
3057 // If we made it here, we didn't find an entry that contained the given address.
3058 error.SetErrorString ("address comes after final region");
3059
3060 if (log)
3061 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3062
3063 return error;
3064}
3065
3066void
3067NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3068{
3069 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3070 if (log)
3071 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3072
3073 {
3074 Mutex::Locker locker (m_mem_region_cache_mutex);
3075 if (log)
3076 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3077 m_mem_region_cache.clear ();
3078 }
3079}
3080
3081Error
3082NativeProcessLinux::AllocateMemory (
3083 lldb::addr_t size,
3084 uint32_t permissions,
3085 lldb::addr_t &addr)
3086{
3087 // FIXME implementing this requires the equivalent of
3088 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3089 // functional ThreadPlans working with Native*Protocol.
3090#if 1
3091 return Error ("not implemented yet");
3092#else
3093 addr = LLDB_INVALID_ADDRESS;
3094
3095 unsigned prot = 0;
3096 if (permissions & lldb::ePermissionsReadable)
3097 prot |= eMmapProtRead;
3098 if (permissions & lldb::ePermissionsWritable)
3099 prot |= eMmapProtWrite;
3100 if (permissions & lldb::ePermissionsExecutable)
3101 prot |= eMmapProtExec;
3102
3103 // TODO implement this directly in NativeProcessLinux
3104 // (and lift to NativeProcessPOSIX if/when that class is
3105 // refactored out).
3106 if (InferiorCallMmap(this, addr, 0, size, prot,
3107 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3108 m_addr_to_mmap_size[addr] = size;
3109 return Error ();
3110 } else {
3111 addr = LLDB_INVALID_ADDRESS;
3112 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3113 }
3114#endif
3115}
3116
3117Error
3118NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3119{
3120 // FIXME see comments in AllocateMemory - required lower-level
3121 // bits not in place yet (ThreadPlans)
3122 return Error ("not implemented");
3123}
3124
3125lldb::addr_t
3126NativeProcessLinux::GetSharedLibraryInfoAddress ()
3127{
3128#if 1
3129 // punt on this for now
3130 return LLDB_INVALID_ADDRESS;
3131#else
3132 // Return the image info address for the exe module
3133#if 1
3134 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3135
3136 ModuleSP module_sp;
3137 Error error = GetExeModuleSP (module_sp);
3138 if (error.Fail ())
3139 {
3140 if (log)
3141 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3142 return LLDB_INVALID_ADDRESS;
3143 }
3144
3145 if (module_sp == nullptr)
3146 {
3147 if (log)
3148 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3149 return LLDB_INVALID_ADDRESS;
3150 }
3151
3152 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3153 if (object_file_sp == nullptr)
3154 {
3155 if (log)
3156 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3157 return LLDB_INVALID_ADDRESS;
3158 }
3159
3160 return obj_file_sp->GetImageInfoAddress();
3161#else
3162 Target *target = &GetTarget();
3163 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3164 Address addr = obj_file->GetImageInfoAddress(target);
3165
3166 if (addr.IsValid())
3167 return addr.GetLoadAddress(target);
3168 return LLDB_INVALID_ADDRESS;
3169#endif
3170#endif // punt on this for now
3171}
3172
3173size_t
3174NativeProcessLinux::UpdateThreads ()
3175{
3176 // The NativeProcessLinux monitoring threads are always up to date
3177 // with respect to thread state and they keep the thread list
3178 // populated properly. All this method needs to do is return the
3179 // thread count.
3180 Mutex::Locker locker (m_threads_mutex);
3181 return m_threads.size ();
3182}
3183
3184bool
3185NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3186{
3187 arch = m_arch;
3188 return true;
3189}
3190
3191Error
3192NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3193{
3194 // FIXME put this behind a breakpoint protocol class that can be
3195 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003196 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003197 static const uint8_t g_i386_opcode [] = { 0xCC };
3198
3199 switch (m_arch.GetMachine ())
3200 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003201 case llvm::Triple::aarch64:
3202 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3203 return Error ();
3204
Todd Fialaaf245d12014-06-30 21:05:18 +00003205 case llvm::Triple::x86:
3206 case llvm::Triple::x86_64:
3207 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3208 return Error ();
3209
3210 default:
3211 assert(false && "CPU type not supported!");
3212 return Error ("CPU type not supported");
3213 }
3214}
3215
3216Error
3217NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3218{
3219 if (hardware)
3220 return Error ("NativeProcessLinux does not support hardware breakpoints");
3221 else
3222 return SetSoftwareBreakpoint (addr, size);
3223}
3224
3225Error
3226NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3227{
3228 // FIXME put this behind a breakpoint protocol class that can be
3229 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003230 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003231 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003232 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003233
3234 switch (m_arch.GetMachine ())
3235 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003236 case llvm::Triple::aarch64:
3237 trap_opcode_bytes = g_aarch64_opcode;
3238 actual_opcode_size = sizeof(g_aarch64_opcode);
3239 return Error ();
3240
Todd Fialaaf245d12014-06-30 21:05:18 +00003241 case llvm::Triple::x86:
3242 case llvm::Triple::x86_64:
3243 trap_opcode_bytes = g_i386_opcode;
3244 actual_opcode_size = sizeof(g_i386_opcode);
3245 return Error ();
3246
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003247 case llvm::Triple::mips64:
3248 case llvm::Triple::mips64el:
3249 trap_opcode_bytes = g_mips64_opcode;
3250 actual_opcode_size = sizeof(g_mips64_opcode);
3251 return Error ();
3252
Todd Fialaaf245d12014-06-30 21:05:18 +00003253 default:
3254 assert(false && "CPU type not supported!");
3255 return Error ("CPU type not supported");
3256 }
3257}
3258
3259#if 0
3260ProcessMessage::CrashReason
3261NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3262{
3263 ProcessMessage::CrashReason reason;
3264 assert(info->si_signo == SIGSEGV);
3265
3266 reason = ProcessMessage::eInvalidCrashReason;
3267
3268 switch (info->si_code)
3269 {
3270 default:
3271 assert(false && "unexpected si_code for SIGSEGV");
3272 break;
3273 case SI_KERNEL:
3274 // Linux will occasionally send spurious SI_KERNEL codes.
3275 // (this is poorly documented in sigaction)
3276 // One way to get this is via unaligned SIMD loads.
3277 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3278 break;
3279 case SEGV_MAPERR:
3280 reason = ProcessMessage::eInvalidAddress;
3281 break;
3282 case SEGV_ACCERR:
3283 reason = ProcessMessage::ePrivilegedAddress;
3284 break;
3285 }
3286
3287 return reason;
3288}
3289#endif
3290
3291
3292#if 0
3293ProcessMessage::CrashReason
3294NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3295{
3296 ProcessMessage::CrashReason reason;
3297 assert(info->si_signo == SIGILL);
3298
3299 reason = ProcessMessage::eInvalidCrashReason;
3300
3301 switch (info->si_code)
3302 {
3303 default:
3304 assert(false && "unexpected si_code for SIGILL");
3305 break;
3306 case ILL_ILLOPC:
3307 reason = ProcessMessage::eIllegalOpcode;
3308 break;
3309 case ILL_ILLOPN:
3310 reason = ProcessMessage::eIllegalOperand;
3311 break;
3312 case ILL_ILLADR:
3313 reason = ProcessMessage::eIllegalAddressingMode;
3314 break;
3315 case ILL_ILLTRP:
3316 reason = ProcessMessage::eIllegalTrap;
3317 break;
3318 case ILL_PRVOPC:
3319 reason = ProcessMessage::ePrivilegedOpcode;
3320 break;
3321 case ILL_PRVREG:
3322 reason = ProcessMessage::ePrivilegedRegister;
3323 break;
3324 case ILL_COPROC:
3325 reason = ProcessMessage::eCoprocessorError;
3326 break;
3327 case ILL_BADSTK:
3328 reason = ProcessMessage::eInternalStackError;
3329 break;
3330 }
3331
3332 return reason;
3333}
3334#endif
3335
3336#if 0
3337ProcessMessage::CrashReason
3338NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3339{
3340 ProcessMessage::CrashReason reason;
3341 assert(info->si_signo == SIGFPE);
3342
3343 reason = ProcessMessage::eInvalidCrashReason;
3344
3345 switch (info->si_code)
3346 {
3347 default:
3348 assert(false && "unexpected si_code for SIGFPE");
3349 break;
3350 case FPE_INTDIV:
3351 reason = ProcessMessage::eIntegerDivideByZero;
3352 break;
3353 case FPE_INTOVF:
3354 reason = ProcessMessage::eIntegerOverflow;
3355 break;
3356 case FPE_FLTDIV:
3357 reason = ProcessMessage::eFloatDivideByZero;
3358 break;
3359 case FPE_FLTOVF:
3360 reason = ProcessMessage::eFloatOverflow;
3361 break;
3362 case FPE_FLTUND:
3363 reason = ProcessMessage::eFloatUnderflow;
3364 break;
3365 case FPE_FLTRES:
3366 reason = ProcessMessage::eFloatInexactResult;
3367 break;
3368 case FPE_FLTINV:
3369 reason = ProcessMessage::eFloatInvalidOperation;
3370 break;
3371 case FPE_FLTSUB:
3372 reason = ProcessMessage::eFloatSubscriptRange;
3373 break;
3374 }
3375
3376 return reason;
3377}
3378#endif
3379
3380#if 0
3381ProcessMessage::CrashReason
3382NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3383{
3384 ProcessMessage::CrashReason reason;
3385 assert(info->si_signo == SIGBUS);
3386
3387 reason = ProcessMessage::eInvalidCrashReason;
3388
3389 switch (info->si_code)
3390 {
3391 default:
3392 assert(false && "unexpected si_code for SIGBUS");
3393 break;
3394 case BUS_ADRALN:
3395 reason = ProcessMessage::eIllegalAlignment;
3396 break;
3397 case BUS_ADRERR:
3398 reason = ProcessMessage::eIllegalAddress;
3399 break;
3400 case BUS_OBJERR:
3401 reason = ProcessMessage::eHardwareError;
3402 break;
3403 }
3404
3405 return reason;
3406}
3407#endif
3408
3409void
3410NativeProcessLinux::ServeOperation(OperationArgs *args)
3411{
3412 NativeProcessLinux *monitor = args->m_monitor;
3413
3414 // We are finised with the arguments and are ready to go. Sync with the
3415 // parent thread and start serving operations on the inferior.
3416 sem_post(&args->m_semaphore);
3417
3418 for(;;)
3419 {
3420 // wait for next pending operation
3421 if (sem_wait(&monitor->m_operation_pending))
3422 {
3423 if (errno == EINTR)
3424 continue;
3425 assert(false && "Unexpected errno from sem_wait");
3426 }
3427
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003428 // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3429 // android. We don't have to send a post to the m_operation_done semaphore because in this
3430 // case the synchronization is achieved by a Join() call
3431 if (monitor->m_operation == EXIT_OPERATION)
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003432 break;
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003433
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003434 static_cast<Operation*>(monitor->m_operation)->Execute(monitor);
Todd Fialaaf245d12014-06-30 21:05:18 +00003435
3436 // notify calling thread that operation is complete
3437 sem_post(&monitor->m_operation_done);
3438 }
3439}
3440
3441void
3442NativeProcessLinux::DoOperation(void *op)
3443{
3444 Mutex::Locker lock(m_operation_mutex);
3445
3446 m_operation = op;
3447
3448 // notify operation thread that an operation is ready to be processed
3449 sem_post(&m_operation_pending);
3450
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003451 // Don't wait for the operation to complete in case of an exit operation. The operation thread
3452 // will exit without posting to the semaphore
3453 if (m_operation == EXIT_OPERATION)
3454 return;
3455
Todd Fialaaf245d12014-06-30 21:05:18 +00003456 // wait for operation to complete
3457 while (sem_wait(&m_operation_done))
3458 {
3459 if (errno == EINTR)
3460 continue;
3461 assert(false && "Unexpected errno from sem_wait");
3462 }
3463}
3464
3465Error
3466NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3467{
3468 ReadOperation op(addr, buf, size, bytes_read);
3469 DoOperation(&op);
3470 return op.GetError ();
3471}
3472
3473Error
3474NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3475{
3476 WriteOperation op(addr, buf, size, bytes_written);
3477 DoOperation(&op);
3478 return op.GetError ();
3479}
3480
Chaoren Lin97ccc292015-02-03 01:51:12 +00003481Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003482NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003483 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003484{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003485 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003486 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003487 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003488}
3489
Chaoren Lin97ccc292015-02-03 01:51:12 +00003490Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003491NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3492 const char* reg_name, const RegisterValue &value)
3493{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003494 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003495 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003496 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003497}
3498
Chaoren Lin97ccc292015-02-03 01:51:12 +00003499Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003500NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3501{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003502 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003503 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003504 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003505}
3506
Chaoren Lin97ccc292015-02-03 01:51:12 +00003507Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003508NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3509{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003510 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003511 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003512 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003513}
3514
Chaoren Lin97ccc292015-02-03 01:51:12 +00003515Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003516NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3517{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003518 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003519 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003520 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003521}
3522
Chaoren Lin97ccc292015-02-03 01:51:12 +00003523Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003524NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3525{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003526 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003527 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003528 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003529}
3530
Chaoren Lin97ccc292015-02-03 01:51:12 +00003531Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003532NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3533{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003534 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003535 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003536 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003537}
3538
Chaoren Lin97ccc292015-02-03 01:51:12 +00003539Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003540NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3541{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003542 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003543 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003544 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003545}
3546
Chaoren Lin97ccc292015-02-03 01:51:12 +00003547Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003548NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3549{
Todd Fialaaf245d12014-06-30 21:05:18 +00003550 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3551
3552 if (log)
3553 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3554 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003555 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003556 DoOperation (&op);
3557 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003558 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3559 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003560}
3561
Chaoren Lin97ccc292015-02-03 01:51:12 +00003562Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003563NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3564{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003565 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003566 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003567 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003568}
3569
Chaoren Lin97ccc292015-02-03 01:51:12 +00003570Error
3571NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003572{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003573 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003574 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003575 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003576}
3577
Chaoren Lin97ccc292015-02-03 01:51:12 +00003578Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003579NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3580{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003581 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003582 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003583 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003584}
3585
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003586Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003587NativeProcessLinux::Detach(lldb::tid_t tid)
3588{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003589 if (tid == LLDB_INVALID_THREAD_ID)
3590 return Error();
3591
3592 DetachOperation op(tid);
3593 DoOperation(&op);
3594 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003595}
3596
3597bool
3598NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3599{
3600 int target_fd = open(path, flags, 0666);
3601
3602 if (target_fd == -1)
3603 return false;
3604
Pavel Labath493c3a12015-02-04 10:36:57 +00003605 if (dup2(target_fd, fd) == -1)
3606 return false;
3607
3608 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003609}
3610
3611void
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003612NativeProcessLinux::StopMonitorThread()
Todd Fialaaf245d12014-06-30 21:05:18 +00003613{
Zachary Turneracee96a2014-09-23 18:32:09 +00003614 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003615 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003616 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00003617 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003618 }
3619}
3620
3621void
3622NativeProcessLinux::StopMonitor()
3623{
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003624 StopMonitorThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003625 StopCoordinatorThread ();
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003626 StopOpThread();
Todd Fialaaf245d12014-06-30 21:05:18 +00003627 sem_destroy(&m_operation_pending);
3628 sem_destroy(&m_operation_done);
3629
3630 // TODO: validate whether this still holds, fix up comment.
3631 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3632 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3633 // the descriptor to a ConnectionFileDescriptor object. Consequently
3634 // even though still has the file descriptor, we shouldn't close it here.
3635}
3636
3637void
3638NativeProcessLinux::StopOpThread()
3639{
Zachary Turneracee96a2014-09-23 18:32:09 +00003640 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003641 return;
3642
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003643 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00003644 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003645}
3646
Chaoren Linfa03ad22015-02-03 01:50:42 +00003647Error
3648NativeProcessLinux::StartCoordinatorThread ()
3649{
3650 Error error;
3651 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3652 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3653
3654 // Skip if thread is already running
3655 if (m_coordinator_thread.IsJoinable())
3656 {
3657 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3658 if (log)
3659 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3660 return error;
3661 }
3662
3663 // Enable verbose logging if lldb thread logging is enabled.
3664 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3665
3666 if (log)
3667 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3668 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3669 return error;
3670}
3671
3672void *
3673NativeProcessLinux::CoordinatorThread (void *arg)
3674{
3675 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3676
3677 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3678 assert (process && "null process passed to CoordinatorThread");
3679 if (!process)
3680 {
3681 if (log)
3682 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3683 return nullptr;
3684 }
3685
3686 // Run the thread state coordinator loop until it is done. This call uses
3687 // efficient waiting for an event to be ready.
3688 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3689 {
3690 }
3691
3692 if (log)
3693 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3694
3695 return nullptr;
3696}
3697
3698void
3699NativeProcessLinux::StopCoordinatorThread()
3700{
3701 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3702 if (log)
3703 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3704
3705 // Tell the coordinator we're done. This will cause the coordinator
3706 // run loop thread to exit when the processing queue hits this message.
3707 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003708 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003709}
3710
Todd Fialaaf245d12014-06-30 21:05:18 +00003711bool
3712NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3713{
3714 for (auto thread_sp : m_threads)
3715 {
3716 assert (thread_sp && "thread list should not contain NULL threads");
3717 if (thread_sp->GetID () == thread_id)
3718 {
3719 // We have this thread.
3720 return true;
3721 }
3722 }
3723
3724 // We don't have this thread.
3725 return false;
3726}
3727
3728NativeThreadProtocolSP
3729NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3730{
3731 // CONSIDER organize threads by map - we can do better than linear.
3732 for (auto thread_sp : m_threads)
3733 {
3734 if (thread_sp->GetID () == thread_id)
3735 return thread_sp;
3736 }
3737
3738 // We don't have this thread.
3739 return NativeThreadProtocolSP ();
3740}
3741
3742bool
3743NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3744{
3745 Mutex::Locker locker (m_threads_mutex);
3746 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3747 {
3748 if (*it && ((*it)->GetID () == thread_id))
3749 {
3750 m_threads.erase (it);
3751 return true;
3752 }
3753 }
3754
3755 // Didn't find it.
3756 return false;
3757}
3758
3759NativeThreadProtocolSP
3760NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3761{
3762 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3763
3764 Mutex::Locker locker (m_threads_mutex);
3765
3766 if (log)
3767 {
3768 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3769 __FUNCTION__,
3770 GetID (),
3771 thread_id);
3772 }
3773
3774 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3775
3776 // If this is the first thread, save it as the current thread
3777 if (m_threads.empty ())
3778 SetCurrentThreadID (thread_id);
3779
3780 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3781 m_threads.push_back (thread_sp);
3782
3783 return thread_sp;
3784}
3785
3786NativeThreadProtocolSP
3787NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3788{
3789 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3790
3791 Mutex::Locker locker (m_threads_mutex);
3792 if (log)
3793 {
3794 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3795 __FUNCTION__,
3796 GetID (),
3797 thread_id);
3798 }
3799
3800 // Retrieve the thread if it is already getting tracked.
3801 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3802 if (thread_sp)
3803 {
3804 if (log)
3805 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3806 __FUNCTION__,
3807 GetID (),
3808 thread_id);
3809 created = false;
3810 return thread_sp;
3811
3812 }
3813
3814 // Create the thread metadata since it isn't being tracked.
3815 if (log)
3816 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3817 __FUNCTION__,
3818 GetID (),
3819 thread_id);
3820
3821 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3822 m_threads.push_back (thread_sp);
3823 created = true;
3824
3825 return thread_sp;
3826}
3827
3828Error
3829NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3830{
Todd Fiala75f47c32014-10-11 21:42:09 +00003831 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003832
3833 Error error;
3834
3835 // Get a linux thread pointer.
3836 if (!thread_sp)
3837 {
3838 error.SetErrorString ("null thread_sp");
3839 if (log)
3840 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3841 return error;
3842 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003843 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003844
3845 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003846 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003847 if (!context_sp)
3848 {
3849 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3850 if (log)
3851 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3852 return error;
3853 }
3854
3855 uint32_t breakpoint_size = 0;
3856 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3857 if (error.Fail ())
3858 {
3859 if (log)
3860 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3861 return error;
3862 }
3863 else
3864 {
3865 if (log)
3866 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3867 }
3868
3869 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3870 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3871 lldb::addr_t breakpoint_addr = initial_pc_addr;
3872 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3873 {
3874 // Do not allow breakpoint probe to wrap around.
3875 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3876 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3877 }
3878
3879 // Check if we stopped because of a breakpoint.
3880 NativeBreakpointSP breakpoint_sp;
3881 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3882 if (!error.Success () || !breakpoint_sp)
3883 {
3884 // We didn't find one at a software probe location. Nothing to do.
3885 if (log)
3886 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3887 return Error ();
3888 }
3889
3890 // If the breakpoint is not a software breakpoint, nothing to do.
3891 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3892 {
3893 if (log)
3894 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3895 return Error ();
3896 }
3897
3898 //
3899 // We have a software breakpoint and need to adjust the PC.
3900 //
3901
3902 // Sanity check.
3903 if (breakpoint_size == 0)
3904 {
3905 // Nothing to do! How did we get here?
3906 if (log)
3907 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);
3908 return Error ();
3909 }
3910
3911 // Change the program counter.
3912 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003913 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 +00003914
3915 error = context_sp->SetPC (breakpoint_addr);
3916 if (error.Fail ())
3917 {
3918 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003919 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 +00003920 return error;
3921 }
3922
3923 return error;
3924}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003925
3926void
3927NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3928{
3929 const bool is_stopped = true;
3930 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3931}
3932
3933void
3934NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3935{
3936 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3937}
3938
3939void
3940NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3941{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003942 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003943}
3944
3945void
3946NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3947 const std::function<void (lldb::tid_t tid)> &call_after_function)
3948{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003949 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3950 if (log)
3951 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3952
Chaoren Linfa03ad22015-02-03 01:50:42 +00003953 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003954 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003955 [=](lldb::tid_t request_stop_tid)
3956 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003957 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003958 },
3959 call_after_function,
3960 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003961}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003962
Chaoren Lin03f12d62015-02-03 01:50:49 +00003963void
3964NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3965 lldb::tid_t skip_stop_request_tid,
3966 const std::function<void (lldb::tid_t tid)> &call_after_function)
3967{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003968 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3969 if (log)
3970 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3971
Chaoren Lin03f12d62015-02-03 01:50:49 +00003972 const lldb::pid_t pid = GetID ();
3973 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3974 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3975 [=](lldb::tid_t request_stop_tid)
3976 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003977 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003978 },
3979 call_after_function,
3980 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003981}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003982
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003983Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003984NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3985{
3986 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3987 if (log)
3988 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3989
3990 Error err;
3991 errno = 0;
3992 if (::tgkill (pid, tid, SIGSTOP) != 0)
3993 {
3994 err.SetErrorToErrno ();
3995 if (log)
3996 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3997 }
3998
3999 return err;
4000}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004001
4002Error
4003NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4004{
4005 char maps_file_name[32];
4006 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4007
4008 FileSpec maps_file_spec(maps_file_name, false);
4009 if (!maps_file_spec.Exists()) {
4010 file_spec.Clear();
4011 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4012 }
4013
4014 FileSpec module_file_spec(module_path, true);
4015
4016 std::ifstream maps_file(maps_file_name);
4017 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4018 StringRef maps_data(maps_data_str.c_str());
4019
4020 while (!maps_data.empty())
4021 {
4022 StringRef maps_row;
4023 std::tie(maps_row, maps_data) = maps_data.split('\n');
4024
4025 SmallVector<StringRef, 16> maps_columns;
4026 maps_row.split(maps_columns, StringRef(" "), -1, false);
4027
4028 if (maps_columns.size() >= 6)
4029 {
4030 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4031 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4032 return Error();
4033 }
4034 }
4035
4036 file_spec.Clear();
4037 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4038 module_file_spec.GetFilename().AsCString(), GetID());
4039}