blob: c00171398f998dfcd06e7c4cfcee7f156c2c3dc2 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
21// C++ Includes
22#include <fstream>
23#include <string>
24
25// Other libraries and framework includes
26#include "lldb/Core/Debugger.h"
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000027#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Core/Error.h"
29#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000030#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Core/RegisterValue.h"
32#include "lldb/Core/Scalar.h"
33#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000034#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000035#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000036#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000037#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000038#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000039#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000041#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044#include "lldb/Utility/PseudoTerminal.h"
45
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000046#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000048#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049#include "NativeThreadLinux.h"
50#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000051#include "Procfs.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000052#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054// System includes - They have to be included after framework includes because they define some
55// macros which collide with variable names in other modules
56#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/personality.h>
58#include <sys/ptrace.h>
59#include <sys/socket.h>
Pavel Labath1107b5a2015-04-17 14:07:49 +000060#include <sys/signalfd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000061#include <sys/syscall.h>
62#include <sys/types.h>
63#include <sys/uio.h>
64#include <sys/user.h>
65#include <sys/wait.h>
66
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000067#if defined (__arm64__) || defined (__aarch64__)
68// NT_PRSTATUS and NT_FPREGSET definition
69#include <elf.h>
70#endif
71
Todd Fialacacde7d2014-09-27 16:54:22 +000072#ifdef __ANDROID__
73#define __ptrace_request int
74#define PT_DETACH PTRACE_DETACH
75#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000076
77#define DEBUG_PTRACE_MAXBYTES 20
78
79// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000080#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000081#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000082 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000083#endif
Todd Fialadda61942014-07-02 21:34:04 +000084#endif
85#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000086#ifndef PTRACE_SETREGS
87 #define PTRACE_SETREGS 13
88#endif
Todd Fialadda61942014-07-02 21:34:04 +000089#endif
90#ifndef PT_GETFPREGS
91#ifndef PTRACE_GETFPREGS
92 #define PTRACE_GETFPREGS 14
93#endif
94#endif
95#ifndef PT_SETFPREGS
96#ifndef PTRACE_SETFPREGS
97 #define PTRACE_SETFPREGS 15
98#endif
99#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000100#ifndef PTRACE_GETREGSET
101 #define PTRACE_GETREGSET 0x4204
102#endif
103#ifndef PTRACE_SETREGSET
104 #define PTRACE_SETREGSET 0x4205
105#endif
106#ifndef PTRACE_GET_THREAD_AREA
107 #define PTRACE_GET_THREAD_AREA 25
108#endif
109#ifndef PTRACE_ARCH_PRCTL
110 #define PTRACE_ARCH_PRCTL 30
111#endif
112#ifndef ARCH_GET_FS
113 #define ARCH_SET_GS 0x1001
114 #define ARCH_SET_FS 0x1002
115 #define ARCH_GET_FS 0x1003
116 #define ARCH_GET_GS 0x1004
117#endif
118
Todd Fiala0bce1b62014-08-17 00:10:50 +0000119#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121// Support hardware breakpoints in case it has not been defined
122#ifndef TRAP_HWBKPT
123 #define TRAP_HWBKPT 4
124#endif
125
126// Try to define a macro to encapsulate the tgkill syscall
127// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000128#define tgkill(pid, tid, sig) \
129 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000130
131// We disable the tracing of ptrace calls for integration builds to
132// avoid the additional indirection and checks.
133#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000134#define PTRACE(req, pid, addr, data, data_size, error) \
135 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000136#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000137#define PTRACE(req, pid, addr, data, data_size, error) \
138 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000139#endif
140
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000141using namespace lldb;
142using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000143using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000144using namespace llvm;
145
Todd Fialaaf245d12014-06-30 21:05:18 +0000146// Private bits we only need internally.
147namespace
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
Pavel Labath1107b5a2015-04-17 14:07:49 +00001073} // end of anonymous namespace
1074
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001075// Simple helper function to ensure flags are enabled on the given file
1076// descriptor.
1077static Error
1078EnsureFDFlags(int fd, int flags)
1079{
1080 Error error;
1081
1082 int status = fcntl(fd, F_GETFL);
1083 if (status == -1)
1084 {
1085 error.SetErrorToErrno();
1086 return error;
1087 }
1088
1089 if (fcntl(fd, F_SETFL, status | flags) == -1)
1090 {
1091 error.SetErrorToErrno();
1092 return error;
1093 }
1094
1095 return error;
1096}
1097
1098// This class encapsulates the privileged thread which performs all ptrace and wait operations on
1099// the inferior. The thread consists of a main loop which waits for events and processes them
1100// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1101// the inferior process. Upon receiving this signal we do a waitpid to get more information
1102// and dispatch to NativeProcessLinux::MonitorCallback.
1103// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1104// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1105// pipe, and the completion of the operation is signalled over the semaphore.
1106// - thread exit event: this is signaled from the Monitor destructor by closing the write end
1107// of the command pipe.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001108class NativeProcessLinux::Monitor {
1109private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001110 // The initial monitor operation (launch or attach). It returns a inferior process id.
1111 std::unique_ptr<InitialOperation> m_initial_operation_up;
1112
1113 ::pid_t m_child_pid = -1;
1114 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001115
1116 enum { READ, WRITE };
1117 int m_pipefd[2] = {-1, -1};
1118 int m_signal_fd = -1;
1119 HostThread m_thread;
1120
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001121 // current operation which must be executed on the priviliged thread
1122 Mutex m_operation_mutex;
1123 Operation *m_operation = nullptr;
1124 sem_t m_operation_sem;
1125 Error m_operation_error;
1126
1127 static constexpr char operation_command = 'o';
1128
Pavel Labath1107b5a2015-04-17 14:07:49 +00001129 void
1130 HandleSignals();
1131
1132 void
1133 HandleWait();
1134
1135 // Returns true if the thread should exit.
1136 bool
1137 HandleCommands();
1138
1139 void
1140 MainLoop();
1141
1142 static void *
1143 RunMonitor(void *arg);
1144
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001145 Error
1146 WaitForOperation();
Pavel Labath1107b5a2015-04-17 14:07:49 +00001147public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001148 Monitor(const InitialOperation &initial_operation,
1149 NativeProcessLinux *native_process)
1150 : m_initial_operation_up(new InitialOperation(initial_operation)),
1151 m_native_process(native_process)
1152 {
1153 sem_init(&m_operation_sem, 0, 0);
1154 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001155
1156 ~Monitor();
1157
1158 Error
1159 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001160
1161 void
1162 DoOperation(Operation *op);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001163};
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001164constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001165
1166Error
1167NativeProcessLinux::Monitor::Initialize()
1168{
1169 Error error;
1170
1171 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1172 // listening for these signals over a signalfd file descriptors. This allows us to wait for
1173 // multiple kinds of events with select.
1174 sigset_t signals;
1175 sigemptyset(&signals);
1176 sigaddset(&signals, SIGCHLD);
1177 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1178 if (m_signal_fd < 0)
1179 {
1180 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1181 __FUNCTION__, strerror(errno));
1182
1183 }
1184
1185 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1186 {
1187 error.SetErrorToErrno();
1188 return error;
1189 }
1190
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001191 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1192 return error;
1193 }
1194
1195 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1196 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001197 if (!m_thread.IsJoinable())
1198 return Error("Failed to create monitor thread for NativeProcessLinux.");
1199
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001200 // Wait for initial operation to complete.
1201 return WaitForOperation();
1202}
1203
1204void
1205NativeProcessLinux::Monitor::DoOperation(Operation *op)
1206{
1207 if (m_thread.EqualsThread(pthread_self())) {
1208 // If we're on the Monitor thread, we can simply execute the operation.
1209 op->Execute(m_native_process);
1210 return;
1211 }
1212
1213 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1214 Mutex::Locker lock(m_operation_mutex);
1215
1216 m_operation = op;
1217
1218 // notify the thread that an operation is ready to be processed
1219 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1220
1221 WaitForOperation();
Todd Fialaaf245d12014-06-30 21:05:18 +00001222}
1223
Pavel Labath1107b5a2015-04-17 14:07:49 +00001224NativeProcessLinux::Monitor::~Monitor()
1225{
1226 if (m_pipefd[WRITE] >= 0)
1227 close(m_pipefd[WRITE]);
1228 if (m_thread.IsJoinable())
1229 m_thread.Join(nullptr);
1230 if (m_pipefd[READ] >= 0)
1231 close(m_pipefd[READ]);
1232 if (m_signal_fd >= 0)
1233 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001234 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001235}
1236
1237void
1238NativeProcessLinux::Monitor::HandleSignals()
1239{
1240 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1241
1242 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1243 // all the information from waitpid(). We just need to read all the signals so that we can
1244 // sleep next time we reach select().
1245 while (true)
1246 {
1247 signalfd_siginfo info;
1248 ssize_t size = read(m_signal_fd, &info, sizeof info);
1249 if (size == -1)
1250 {
1251 if (errno == EAGAIN || errno == EWOULDBLOCK)
1252 break; // We are done.
1253 if (errno == EINTR)
1254 continue;
1255 if (log)
1256 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1257 __FUNCTION__, strerror(errno));
1258 break;
1259 }
1260 if (size != sizeof info)
1261 {
1262 // We got incomplete information structure. This should not happen, let's just log
1263 // that.
1264 if (log)
1265 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1266 "structure size is %zd, read returned %zd bytes",
1267 __FUNCTION__, sizeof info, size);
1268 break;
1269 }
1270 if (log)
1271 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1272 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1273 }
1274}
1275
1276void
1277NativeProcessLinux::Monitor::HandleWait()
1278{
1279 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1280 // Process all pending waitpid notifications.
1281 while (true)
1282 {
1283 int status = -1;
1284 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1285
1286 if (wait_pid == 0)
1287 break; // We are done.
1288
1289 if (wait_pid == -1)
1290 {
1291 if (errno == EINTR)
1292 continue;
1293
1294 if (log)
1295 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1296 __FUNCTION__, m_child_pid, strerror(errno));
1297 break;
1298 }
1299
1300 bool exited = false;
1301 int signal = 0;
1302 int exit_status = 0;
1303 const char *status_cstr = NULL;
1304 if (WIFSTOPPED(status))
1305 {
1306 signal = WSTOPSIG(status);
1307 status_cstr = "STOPPED";
1308 }
1309 else if (WIFEXITED(status))
1310 {
1311 exit_status = WEXITSTATUS(status);
1312 status_cstr = "EXITED";
1313 exited = true;
1314 }
1315 else if (WIFSIGNALED(status))
1316 {
1317 signal = WTERMSIG(status);
1318 status_cstr = "SIGNALED";
1319 if (wait_pid == abs(m_child_pid)) {
1320 exited = true;
1321 exit_status = -1;
1322 }
1323 }
1324 else
1325 status_cstr = "(\?\?\?)";
1326
1327 if (log)
1328 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1329 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1330 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1331
1332 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1333 }
1334}
1335
1336bool
1337NativeProcessLinux::Monitor::HandleCommands()
1338{
1339 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1340
1341 while (true)
1342 {
1343 char command = 0;
1344 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1345 if (size == -1)
1346 {
1347 if (errno == EAGAIN || errno == EWOULDBLOCK)
1348 return false;
1349 if (errno == EINTR)
1350 continue;
1351 if (log)
1352 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1353 return true;
1354 }
1355 if (size == 0) // end of file - write end closed
1356 {
1357 if (log)
1358 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
1359 return true; // We are done.
1360 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001361
1362 switch (command)
1363 {
1364 case operation_command:
1365 m_operation->Execute(m_native_process);
1366
1367 // notify calling thread that operation is complete
1368 sem_post(&m_operation_sem);
1369 break;
1370 default:
1371 if (log)
1372 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1373 __FUNCTION__, command);
1374 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001375 }
1376}
1377
1378void
1379NativeProcessLinux::Monitor::MainLoop()
1380{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001381 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1382 m_initial_operation_up.reset();
1383 m_child_pid = -getpgid(child_pid),
1384 sem_post(&m_operation_sem);
1385
Pavel Labath1107b5a2015-04-17 14:07:49 +00001386 while (true)
1387 {
1388 fd_set fds;
1389 FD_ZERO(&fds);
1390 FD_SET(m_signal_fd, &fds);
1391 FD_SET(m_pipefd[READ], &fds);
1392
1393 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1394 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1395 if (r < 0)
1396 {
1397 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1398 if (log)
1399 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1400 __FUNCTION__, strerror(errno));
1401 return;
1402 }
1403
1404 if (FD_ISSET(m_pipefd[READ], &fds))
1405 {
1406 if (HandleCommands())
1407 return;
1408 }
1409
1410 if (FD_ISSET(m_signal_fd, &fds))
1411 {
1412 HandleSignals();
1413 HandleWait();
1414 }
1415 }
1416}
1417
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001418Error
1419NativeProcessLinux::Monitor::WaitForOperation()
1420{
1421 Error error;
1422 while (sem_wait(&m_operation_sem) != 0)
1423 {
1424 if (errno == EINTR)
1425 continue;
1426
1427 error.SetErrorToErrno();
1428 return error;
1429 }
1430
1431 return m_operation_error;
1432}
1433
Pavel Labath1107b5a2015-04-17 14:07:49 +00001434void *
1435NativeProcessLinux::Monitor::RunMonitor(void *arg)
1436{
1437 static_cast<Monitor *>(arg)->MainLoop();
1438 return nullptr;
1439}
1440
1441
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001442NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001443 char const **argv,
1444 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001445 const std::string &stdin_path,
1446 const std::string &stdout_path,
1447 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001448 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001449 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001450 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +00001451 m_argv(argv),
1452 m_envp(envp),
1453 m_stdin_path(stdin_path),
1454 m_stdout_path(stdout_path),
1455 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001456 m_working_dir(working_dir),
1457 m_launch_info(launch_info)
1458{
1459}
Todd Fialaaf245d12014-06-30 21:05:18 +00001460
1461NativeProcessLinux::LaunchArgs::~LaunchArgs()
1462{ }
1463
Todd Fialaaf245d12014-06-30 21:05:18 +00001464// -----------------------------------------------------------------------------
1465// Public Static Methods
1466// -----------------------------------------------------------------------------
1467
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001468Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001469NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001470 Module *exe_module,
1471 ProcessLaunchInfo &launch_info,
1472 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001473 NativeProcessProtocolSP &native_process_sp)
1474{
1475 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1476
1477 Error error;
1478
1479 // Verify the working directory is valid if one was specified.
1480 const char* working_dir = launch_info.GetWorkingDirectory ();
1481 if (working_dir)
1482 {
1483 FileSpec working_dir_fs (working_dir, true);
1484 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1485 {
1486 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1487 return error;
1488 }
1489 }
1490
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001491 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001492
1493 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001494 std::string stdin_path;
1495 std::string stdout_path;
1496 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001497
1498 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001499 if (file_action)
1500 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001501
1502 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001503 if (file_action)
1504 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001505
1506 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001507 if (file_action)
1508 stderr_path = file_action->GetPath ();
1509
1510 if (log)
1511 {
1512 if (!stdin_path.empty ())
1513 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1514 else
1515 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1516
1517 if (!stdout_path.empty ())
1518 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1519 else
1520 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1521
1522 if (!stderr_path.empty ())
1523 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1524 else
1525 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1526 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001527
1528 // Create the NativeProcessLinux in launch mode.
1529 native_process_sp.reset (new NativeProcessLinux ());
1530
1531 if (log)
1532 {
1533 int i = 0;
1534 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1535 {
1536 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1537 ++i;
1538 }
1539 }
1540
1541 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1542 {
1543 native_process_sp.reset ();
1544 error.SetErrorStringWithFormat ("failed to register the native delegate");
1545 return error;
1546 }
1547
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001548 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001549 exe_module,
1550 launch_info.GetArguments ().GetConstArgumentVector (),
1551 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1552 stdin_path,
1553 stdout_path,
1554 stderr_path,
1555 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001556 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001557 error);
1558
1559 if (error.Fail ())
1560 {
1561 native_process_sp.reset ();
1562 if (log)
1563 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1564 return error;
1565 }
1566
1567 launch_info.SetProcessID (native_process_sp->GetID ());
1568
1569 return error;
1570}
1571
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001572Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001573NativeProcessLinux::AttachToProcess (
1574 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001575 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001576 NativeProcessProtocolSP &native_process_sp)
1577{
1578 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1579 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1580 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1581
1582 // Grab the current platform architecture. This should be Linux,
1583 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001584 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001585 if (!platform_sp)
1586 return Error("failed to get a valid default platform");
1587
1588 // Retrieve the architecture for the running process.
1589 ArchSpec process_arch;
1590 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1591 if (!error.Success ())
1592 return error;
1593
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001594 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001595
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001596 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001597 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001598 error.SetErrorStringWithFormat ("failed to register the native delegate");
1599 return error;
1600 }
1601
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001602 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001603 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001604 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001605
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001606 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001607 return error;
1608}
1609
1610// -----------------------------------------------------------------------------
1611// Public Instance Methods
1612// -----------------------------------------------------------------------------
1613
1614NativeProcessLinux::NativeProcessLinux () :
1615 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1616 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001617 m_supports_mem_region (eLazyBoolCalculate),
1618 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001619 m_mem_region_cache_mutex (),
1620 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1621 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001622{
1623}
1624
1625//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001626// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1627// Refer to Monitor and Operation classes to see why this is necessary.
1628//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001629void
1630NativeProcessLinux::LaunchInferior (
1631 Module *module,
1632 const char *argv[],
1633 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001634 const std::string &stdin_path,
1635 const std::string &stdout_path,
1636 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001637 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001638 const ProcessLaunchInfo &launch_info,
1639 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001640{
1641 if (module)
1642 m_arch = module->GetArchitecture ();
1643
Chaoren Linfa03ad22015-02-03 01:50:42 +00001644 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001645
1646 std::unique_ptr<LaunchArgs> args(
1647 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001648 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001649 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001650 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001651
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001652 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001653 if (!error.Success ())
1654 return;
1655
1656 error = StartCoordinatorThread ();
1657 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001658 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001659}
1660
1661void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001662NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001663{
1664 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1665 if (log)
1666 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1667
1668 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001669 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001670 if (!platform_sp)
1671 {
1672 if (log)
1673 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1674 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001675 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001676 }
1677
1678 // Gather info about the process.
1679 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001680 if (!platform_sp->GetProcessInfo (pid, process_info))
1681 {
1682 if (log)
1683 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1684 error.SetErrorString ("failed to get process info");
1685 return;
1686 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001687
1688 // Resolve the executable module
1689 ModuleSP exe_module_sp;
1690 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001691 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001692 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001693 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 if (!error.Success())
1695 return;
1696
1697 // Set the architecture to the exe architecture.
1698 m_arch = exe_module_sp->GetArchitecture();
1699 if (log)
1700 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1701
1702 m_pid = pid;
1703 SetState(eStateAttaching);
1704
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001705 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001706 if (!error.Success ())
1707 return;
1708
Chaoren Linfa03ad22015-02-03 01:50:42 +00001709 error = StartCoordinatorThread ();
1710 if (!error.Success ())
1711 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001712}
1713
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001714void
1715NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001716{
1717 StopMonitor();
1718}
1719
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001720::pid_t
1721NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001722{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001723 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001724
1725 const char **argv = args->m_argv;
1726 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001727 const char *working_dir = args->m_working_dir;
1728
1729 lldb_utility::PseudoTerminal terminal;
1730 const size_t err_len = 1024;
1731 char err_str[err_len];
1732 lldb::pid_t pid;
1733 NativeThreadProtocolSP thread_sp;
1734
1735 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001736
1737 // Propagate the environment if one is not supplied.
1738 if (envp == NULL || envp[0] == NULL)
1739 envp = const_cast<const char **>(environ);
1740
1741 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1742 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001743 error.SetErrorToGenericError();
1744 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1745 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001746 }
1747
1748 // Recognized child exit status codes.
1749 enum {
1750 ePtraceFailed = 1,
1751 eDupStdinFailed,
1752 eDupStdoutFailed,
1753 eDupStderrFailed,
1754 eChdirFailed,
1755 eExecFailed,
1756 eSetGidFailed
1757 };
1758
1759 // Child process.
1760 if (pid == 0)
1761 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001762 // FIXME consider opening a pipe between parent/child and have this forked child
1763 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001764
Todd Fiala75f47c32014-10-11 21:42:09 +00001765 // Start tracing this child that is about to exec.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001766 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1767 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001769
Pavel Labath493c3a12015-02-04 10:36:57 +00001770 // terminal has already dupped the tty descriptors to stdin/out/err.
1771 // This closes original fd from which they were copied (and avoids
1772 // leaking descriptors to the debugged process.
1773 terminal.CloseSlaveFileDescriptor();
1774
Todd Fialaaf245d12014-06-30 21:05:18 +00001775 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001776 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001777 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001778
1779 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001780 if (setpgid(0, 0) != 0)
1781 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001782 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001783 // Don't allow this to prevent an inferior exec.
1784 }
1785
1786 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001787 if (!args->m_stdin_path.empty ())
1788 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001789 exit(eDupStdinFailed);
1790
Todd Fiala75f47c32014-10-11 21:42:09 +00001791 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001792 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001793 exit(eDupStdoutFailed);
1794
Todd Fiala75f47c32014-10-11 21:42:09 +00001795 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001796 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001797 exit(eDupStderrFailed);
1798
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001799 // Close everything besides stdin, stdout, and stderr that has no file
1800 // action to avoid leaking
1801 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1802 if (!args->m_launch_info.GetFileActionForFD(fd))
1803 close(fd);
1804
Todd Fialaaf245d12014-06-30 21:05:18 +00001805 // Change working directory
1806 if (working_dir != NULL && working_dir[0])
1807 if (0 != ::chdir(working_dir))
1808 exit(eChdirFailed);
1809
Todd Fiala0bce1b62014-08-17 00:10:50 +00001810 // Disable ASLR if requested.
1811 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1812 {
1813 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1814 if (old_personality == -1)
1815 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001816 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001817 }
1818 else
1819 {
1820 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1821 if (new_personality == -1)
1822 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001823 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001824 }
1825 else
1826 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001827 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001828 }
1829 }
1830 }
1831
Todd Fiala75f47c32014-10-11 21:42:09 +00001832 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001833 execve(argv[0],
1834 const_cast<char *const *>(argv),
1835 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001836
1837 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001838 exit(eExecFailed);
1839 }
1840
Todd Fiala75f47c32014-10-11 21:42:09 +00001841 //
1842 // This is the parent code here.
1843 //
1844 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1845
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 // Wait for the child process to trap on its call to execve.
1847 ::pid_t wpid;
1848 int status;
1849 if ((wpid = waitpid(pid, &status, 0)) < 0)
1850 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001851 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001852 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001853 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1854 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001855
1856 // Mark the inferior as invalid.
1857 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001858 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001859
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001860 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001861 }
1862 else if (WIFEXITED(status))
1863 {
1864 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001865 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001866 switch (WEXITSTATUS(status))
1867 {
1868 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001869 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001870 break;
1871 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001872 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001873 break;
1874 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001875 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001876 break;
1877 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001878 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001879 break;
1880 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001881 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001882 break;
1883 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001884 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001885 break;
1886 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001887 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001888 break;
1889 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001890 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001891 break;
1892 }
1893
1894 if (log)
1895 {
1896 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1897 __FUNCTION__,
1898 WEXITSTATUS(status));
1899 }
1900
1901 // Mark the inferior as invalid.
1902 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001903 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001904
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001905 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001906 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001907 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001908 "Could not sync with inferior process.");
1909
1910 if (log)
1911 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1912
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001913 error = SetDefaultPtraceOpts(pid);
1914 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001915 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001916 if (log)
1917 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001918 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001919
1920 // Mark the inferior as invalid.
1921 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001922 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001923
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001924 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001925 }
1926
1927 // Release the master terminal descriptor and pass it off to the
1928 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001929 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1930 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001931
1932 // Set the terminal fd to be in non blocking mode (it simplifies the
1933 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1934 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001935 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1936 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001937 {
1938 if (log)
1939 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001940 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001941
1942 // Mark the inferior as invalid.
1943 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001944 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001945
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001946 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001947 }
1948
1949 if (log)
1950 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1951
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001952 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001953 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001954 NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001955 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001956
1957 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001958 SetCurrentThreadID (thread_sp->GetID ());
1959 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001960
Todd Fialaaf245d12014-06-30 21:05:18 +00001961 if (log)
1962 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001963 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001964 {
1965 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1966 }
1967 else
1968 {
1969 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001970 __FUNCTION__, error.AsCString ());
1971 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001972 }
1973 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001974 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001975}
1976
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001977::pid_t
1978NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001979{
Todd Fialaaf245d12014-06-30 21:05:18 +00001980 lldb::ThreadSP inferior;
1981 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1982
1983 // Use a map to keep track of the threads which we have attached/need to attach.
1984 Host::TidMap tids_to_attach;
1985 if (pid <= 1)
1986 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001987 error.SetErrorToGenericError();
1988 error.SetErrorString("Attaching to process 1 is not allowed.");
1989 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001990 }
1991
1992 while (Host::FindProcessThreads(pid, tids_to_attach))
1993 {
1994 for (Host::TidMap::iterator it = tids_to_attach.begin();
1995 it != tids_to_attach.end();)
1996 {
1997 if (it->second == false)
1998 {
1999 lldb::tid_t tid = it->first;
2000
2001 // Attach to the requested process.
2002 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002003 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
2004 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002005 {
2006 // No such thread. The thread may have exited.
2007 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002008 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00002009 {
2010 it = tids_to_attach.erase(it);
2011 continue;
2012 }
2013 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002014 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002015 }
2016
2017 int status;
2018 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2019 // At this point we should have a thread stopped if waitpid succeeds.
2020 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2021 {
2022 // No such thread. The thread may have exited.
2023 // More error handling may be needed.
2024 if (errno == ESRCH)
2025 {
2026 it = tids_to_attach.erase(it);
2027 continue;
2028 }
2029 else
2030 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002031 error.SetErrorToErrno();
2032 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002033 }
2034 }
2035
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002036 error = SetDefaultPtraceOpts(tid);
2037 if (error.Fail())
2038 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002039
2040 if (log)
2041 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2042
2043 it->second = true;
2044
2045 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002046 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00002047 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002048
2049 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002050 NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002051 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002052 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002053 }
2054
2055 // move the loop forward
2056 ++it;
2057 }
2058 }
2059
2060 if (tids_to_attach.size() > 0)
2061 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002062 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002063 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002064 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002065 }
2066 else
2067 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002068 error.SetErrorToGenericError();
2069 error.SetErrorString("No such process.");
2070 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002071 }
2072
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002073 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002074}
2075
Chaoren Lin97ccc292015-02-03 01:51:12 +00002076Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002077NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2078{
2079 long ptrace_opts = 0;
2080
2081 // Have the child raise an event on exit. This is used to keep the child in
2082 // limbo until it is destroyed.
2083 ptrace_opts |= PTRACE_O_TRACEEXIT;
2084
2085 // Have the tracer trace threads which spawn in the inferior process.
2086 // TODO: if we want to support tracing the inferiors' child, add the
2087 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2088 ptrace_opts |= PTRACE_O_TRACECLONE;
2089
2090 // Have the tracer notify us before execve returns
2091 // (needed to disable legacy SIGTRAP generation)
2092 ptrace_opts |= PTRACE_O_TRACEEXEC;
2093
Chaoren Lin97ccc292015-02-03 01:51:12 +00002094 Error error;
2095 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2096 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002097}
2098
2099static ExitType convert_pid_status_to_exit_type (int status)
2100{
2101 if (WIFEXITED (status))
2102 return ExitType::eExitTypeExit;
2103 else if (WIFSIGNALED (status))
2104 return ExitType::eExitTypeSignal;
2105 else if (WIFSTOPPED (status))
2106 return ExitType::eExitTypeStop;
2107 else
2108 {
2109 // We don't know what this is.
2110 return ExitType::eExitTypeInvalid;
2111 }
2112}
2113
2114static int convert_pid_status_to_return_code (int status)
2115{
2116 if (WIFEXITED (status))
2117 return WEXITSTATUS (status);
2118 else if (WIFSIGNALED (status))
2119 return WTERMSIG (status);
2120 else if (WIFSTOPPED (status))
2121 return WSTOPSIG (status);
2122 else
2123 {
2124 // We don't know what this is.
2125 return ExitType::eExitTypeInvalid;
2126 }
2127}
2128
Pavel Labath1107b5a2015-04-17 14:07:49 +00002129// Handles all waitpid events from the inferior process.
2130void
2131NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00002132 bool exited,
2133 int signal,
2134 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00002135{
2136 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2137
Todd Fialaaf245d12014-06-30 21:05:18 +00002138 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002139 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002140
2141 // Handle when the thread exits.
2142 if (exited)
2143 {
2144 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002145 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 +00002146
2147 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002148 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002149
Chaoren Linfa03ad22015-02-03 01:50:42 +00002150 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002151 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002152
Todd Fialaaf245d12014-06-30 21:05:18 +00002153 if (is_main_thread)
2154 {
2155 // We only set the exit status and notify the delegate if we haven't already set the process
2156 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2157 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002158 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00002159 if (!already_notified)
2160 {
2161 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002162 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 (GetState ()));
Todd Fialaaf245d12014-06-30 21:05:18 +00002163 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002164 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002165
2166 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002167 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002168 }
2169 else
2170 {
2171 if (log)
2172 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2173 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002174 }
2175 else
2176 {
2177 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2178 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2179 // and we would have done an all-stop then.
2180 if (log)
2181 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +00002182 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00002183 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00002184 }
2185
2186 // Get details on the signal raised.
2187 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00002188 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00002189 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002190 {
2191 // We have retrieved the signal info. Dispatch appropriately.
2192 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002193 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002194 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00002195 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002196 }
2197 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002198 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002199 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002200 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002201 // This is a group stop reception for this tid.
2202 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002203 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
2204 NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002205 }
2206 else
2207 {
2208 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2209
2210 // A return value of ESRCH means the thread/process is no longer on the system,
2211 // so it was killed somehow outside of our control. Either way, we can't do anything
2212 // with it anymore.
2213
Todd Fialaaf245d12014-06-30 21:05:18 +00002214 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002215 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002216
Chaoren Linfa03ad22015-02-03 01:50:42 +00002217 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002218 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002219
Todd Fialaaf245d12014-06-30 21:05:18 +00002220 if (log)
2221 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002222 __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 +00002223
2224 if (is_main_thread)
2225 {
2226 // Notify the delegate - our process is not available but appears to have been killed outside
2227 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00002228 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2229 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002230 }
2231 else
2232 {
2233 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2234 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002235 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__, GetID (), pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002236 }
2237 }
2238 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002239}
2240
2241void
2242NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2243{
2244 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2245 const bool is_main_thread = (pid == GetID ());
2246
2247 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2248 if (!info)
2249 return;
2250
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002251 Mutex::Locker locker (m_threads_mutex);
2252
Todd Fialaaf245d12014-06-30 21:05:18 +00002253 // See if we can find a thread for this signal.
2254 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2255 if (!thread_sp)
2256 {
2257 if (log)
2258 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2259 }
2260
2261 switch (info->si_code)
2262 {
2263 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2264 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2265 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2266
2267 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2268 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002269 // This is the notification on the parent thread which informs us of new thread
2270 // creation. We are not interested in these events at this point (an interesting use
2271 // case would be to stop the process upon thread creation), so we just resume the thread.
2272 // We will pickup the new thread when we get its SIGSTOP notification.
Todd Fialaaf245d12014-06-30 21:05:18 +00002273
Pavel Labath5fd24c62015-04-23 09:04:35 +00002274 if (log)
Todd Fialaaf245d12014-06-30 21:05:18 +00002275 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002276 unsigned long event_message = 0;
2277 if (GetEventMessage (pid, &event_message).Success())
2278 {
2279 lldb::tid_t tid = static_cast<lldb::tid_t> (event_message);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002280 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002281
Chaoren Linfa03ad22015-02-03 01:50:42 +00002282 }
2283 else
Chaoren Linfa03ad22015-02-03 01:50:42 +00002284 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 +00002285 }
2286
Pavel Labath5fd24c62015-04-23 09:04:35 +00002287 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002288 break;
2289 }
2290
2291 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002292 {
2293 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002294 if (log)
2295 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002296
Chaoren Linfa03ad22015-02-03 01:50:42 +00002297 // The thread state coordinator needs to reset due to the exec.
2298 m_coordinator_up->ResetForExec ();
2299
2300 // 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 +00002301 if (log)
2302 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2303
2304 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002305 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002306 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2307 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002308 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002309 main_thread_sp = thread_sp;
2310 if (log)
2311 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002312 }
2313 else
2314 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002315 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002316 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002317 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002318 }
2319 }
2320
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002321 m_threads.clear ();
2322
2323 if (main_thread_sp)
2324 {
2325 m_threads.push_back (main_thread_sp);
2326 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002327 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002328 }
2329 else
2330 {
2331 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2332 if (log)
2333 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2334 }
2335
Chaoren Linfa03ad22015-02-03 01:50:42 +00002336 // Tell coordinator about about the "new" (since exec) stopped main thread.
2337 const lldb::tid_t main_thread_tid = GetID ();
2338 NotifyThreadCreateStopped (main_thread_tid);
2339
2340 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2341 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002342 // Let our delegate know we have just exec'd.
2343 NotifyDidExec ();
2344
2345 // If we have a main thread, indicate we are stopped.
2346 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002347
2348 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002349 CallAfterRunningThreadsStop (pid,
2350 [=] (lldb::tid_t signaling_tid)
2351 {
2352 SetState (StateType::eStateStopped, true);
2353 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002354
Todd Fialaaf245d12014-06-30 21:05:18 +00002355 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002356 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002357
2358 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2359 {
2360 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002361
2362 // This thread is currently stopped. It's not actually dead yet, just about to be.
2363 NotifyThreadStop (pid);
2364
Todd Fialaaf245d12014-06-30 21:05:18 +00002365 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002366 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002367 data = -1;
2368
2369 if (log)
2370 {
2371 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2372 __FUNCTION__,
2373 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2374 pid,
2375 is_main_thread ? "is main thread" : "not main thread");
2376 }
2377
Todd Fialaaf245d12014-06-30 21:05:18 +00002378 if (is_main_thread)
2379 {
2380 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002381 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002382
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002383 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002384 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002385 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002386 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002387 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002388 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002389 },
2390 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002391
2392 break;
2393 }
2394
2395 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002396 case TRAP_TRACE: // We receive this on single stepping.
2397 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002398 if (thread_sp)
2399 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002400 // If a watchpoint was hit, report it
2401 uint32_t wp_index;
2402 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2403 if (error.Fail() && log)
2404 log->Printf("NativeProcessLinux::%s() "
2405 "received error while checking for watchpoint hits, "
2406 "pid = %" PRIu64 " error = %s",
2407 __FUNCTION__, pid, error.AsCString());
2408 if (wp_index != LLDB_INVALID_INDEX32)
2409 {
2410 MonitorWatchpoint(pid, thread_sp, wp_index);
2411 break;
2412 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002413 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002414 // Otherwise, report step over
2415 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002416 break;
2417
2418 case SI_KERNEL:
2419 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002420 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002421 break;
2422
2423 case SIGTRAP:
2424 case (SIGTRAP | 0x80):
2425 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002426 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2427
2428 // This thread is currently stopped.
2429 NotifyThreadStop (pid);
2430 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002431 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002432
2433
Todd Fialaaf245d12014-06-30 21:05:18 +00002434 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002435 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002436 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002437 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002438 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002439 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002440 },
2441 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002442 break;
2443
2444 default:
2445 assert(false && "Unexpected SIGTRAP code!");
2446 if (log)
2447 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)));
2448 break;
2449
2450 }
2451}
2452
2453void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002454NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2455{
2456 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2457 if (log)
2458 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2459 __FUNCTION__, pid);
2460
2461 if (thread_sp)
2462 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2463
2464 // This thread is currently stopped.
2465 NotifyThreadStop(pid);
2466
2467 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2468 // This would have already happened at the time the Resume() with step operation was signaled.
2469 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2470 // once all running threads have checked in as stopped.
2471 SetCurrentThreadID(pid);
2472 // Tell the process we have a stop (from software breakpoint).
2473 CallAfterRunningThreadsStop(pid,
2474 [=](lldb::tid_t signaling_tid)
2475 {
2476 SetState(StateType::eStateStopped, true);
2477 });
2478}
2479
2480void
2481NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2482{
2483 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2484 if (log)
2485 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2486 __FUNCTION__, pid);
2487
2488 // This thread is currently stopped.
2489 NotifyThreadStop(pid);
2490
2491 // Mark the thread as stopped at breakpoint.
2492 if (thread_sp)
2493 {
2494 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2495 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2496 if (error.Fail())
2497 if (log)
2498 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2499 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002500
2501 auto it = m_threads_stepping_with_breakpoint.find(pid);
2502 if (it != m_threads_stepping_with_breakpoint.end())
2503 {
2504 Error error = RemoveBreakpoint (it->second);
2505 if (error.Fail())
2506 if (log)
2507 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2508 __FUNCTION__, pid, error.AsCString());
2509
2510 m_threads_stepping_with_breakpoint.erase(it);
2511 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2512 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002513 }
2514 else
2515 if (log)
2516 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2517 "warning, cannot process software breakpoint since no thread metadata",
2518 __FUNCTION__, pid);
2519
2520
2521 // We need to tell all other running threads before we notify the delegate about this stop.
2522 CallAfterRunningThreadsStop(pid,
2523 [=](lldb::tid_t deferred_notification_tid)
2524 {
2525 SetCurrentThreadID(deferred_notification_tid);
2526 // Tell the process we have a stop (from software breakpoint).
2527 SetState(StateType::eStateStopped, true);
2528 });
2529}
2530
2531void
2532NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2533{
2534 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2535 if (log)
2536 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2537 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2538 __FUNCTION__, pid, wp_index);
2539
2540 // This thread is currently stopped.
2541 NotifyThreadStop(pid);
2542
2543 // Mark the thread as stopped at watchpoint.
2544 // The address is at (lldb::addr_t)info->si_addr if we need it.
2545 lldbassert(thread_sp && "thread_sp cannot be NULL");
2546 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2547
2548 // We need to tell all other running threads before we notify the delegate about this stop.
2549 CallAfterRunningThreadsStop(pid,
2550 [=](lldb::tid_t deferred_notification_tid)
2551 {
2552 SetCurrentThreadID(deferred_notification_tid);
2553 // Tell the process we have a stop (from watchpoint).
2554 SetState(StateType::eStateStopped, true);
2555 });
2556}
2557
2558void
Todd Fialaaf245d12014-06-30 21:05:18 +00002559NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2560{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002561 assert (info && "null info");
2562 if (!info)
2563 return;
2564
2565 const int signo = info->si_signo;
2566 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002567
2568 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2569
2570 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2571 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2572 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2573 //
2574 // IOW, user generated signals never generate what we consider to be a
2575 // "crash".
2576 //
2577 // Similarly, ACK signals generated by this monitor.
2578
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002579 Mutex::Locker locker (m_threads_mutex);
2580
Todd Fialaaf245d12014-06-30 21:05:18 +00002581 // See if we can find a thread for this signal.
2582 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2583 if (!thread_sp)
2584 {
2585 if (log)
2586 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2587 }
2588
2589 // Handle the signal.
2590 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2591 {
2592 if (log)
2593 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2594 __FUNCTION__,
2595 GetUnixSignals ().GetSignalAsCString (signo),
2596 signo,
2597 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2598 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002599 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002600 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002601 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002602
Todd Fiala58a2f662014-08-12 17:02:07 +00002603 // Check for new thread notification.
2604 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2605 {
2606 // A new thread creation is being signaled. This is one of two parts that come in
2607 // a non-deterministic order. pid is the thread id.
2608 if (log)
2609 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2610 __FUNCTION__, GetID (), pid);
2611
Pavel Labath5fd24c62015-04-23 09:04:35 +00002612 thread_sp = AddThread(pid);
2613 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2614 // We can now resume the newly created thread.
2615 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2616 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2617 m_coordinator_up->NotifyThreadCreate (pid, false, CoordinatorErrorHandler);
Todd Fiala58a2f662014-08-12 17:02:07 +00002618 // Done handling.
2619 return;
2620 }
2621
2622 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002623 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002624 {
2625 // This is a tgkill()-based stop.
2626 if (thread_sp)
2627 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002628 if (log)
2629 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2630 __FUNCTION__,
2631 GetID (),
2632 pid);
2633
Chaoren Linaab58632015-02-03 01:50:57 +00002634 // Check that we're not already marked with a stop reason.
2635 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2636 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2637 // and that, without an intervening resume, we received another stop. It is more likely
2638 // that we are missing the marking of a run state somewhere if we find that the thread was
2639 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002640 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2641 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002642
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002643 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002644 if (!StateIsStoppedState (thread_state, false))
2645 {
2646 // An inferior thread just stopped, but was not the primary cause of the process stop.
2647 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2648 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002649 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002650 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002651 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002652 }
2653 else
2654 {
2655 if (log)
2656 {
2657 // Retrieve the signal name if the thread was stopped by a signal.
2658 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002659 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002660 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2661 if (!signal_name)
2662 signal_name = "<no-signal-name>";
2663
2664 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",
2665 __FUNCTION__,
2666 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002667 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002668 StateAsCString (thread_state),
2669 stop_signo,
2670 signal_name);
2671 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002672 // Tell the thread state coordinator about the stop.
2673 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002674 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002675 }
2676
2677 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002678 return;
2679 }
2680
2681 if (log)
2682 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2683
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002684 // This thread is stopped.
2685 NotifyThreadStop (pid);
2686
Todd Fialaaf245d12014-06-30 21:05:18 +00002687 switch (signo)
2688 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002689 case SIGSTOP:
2690 {
2691 if (log)
2692 {
2693 if (is_from_llgs)
2694 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2695 else
2696 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2697 }
2698
Chaoren Linfa03ad22015-02-03 01:50:42 +00002699 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2700 // This thread will get stopped again as part of the group-stop completion.
2701 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002702 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002703 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002704 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002705 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002706 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002707 },
2708 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002709 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002710 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002711 case SIGSEGV:
2712 case SIGILL:
2713 case SIGFPE:
2714 case SIGBUS:
2715 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002716 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002717 break;
2718 default:
2719 // This is just a pre-signal-delivery notification of the incoming signal.
2720 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002721 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002722
2723 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002724 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002725
2726 // Send a stop to the debugger after we get all other threads to stop.
2727 CallAfterRunningThreadsStop (pid,
2728 [=] (lldb::tid_t signaling_tid)
2729 {
2730 SetCurrentThreadID (signaling_tid);
2731 SetState (StateType::eStateStopped, true);
2732 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002733}
2734
Tamas Berghammere7708682015-04-22 10:00:23 +00002735namespace {
2736
2737struct EmulatorBaton
2738{
2739 NativeProcessLinux* m_process;
2740 NativeRegisterContext* m_reg_context;
2741 RegisterValue m_pc;
2742 RegisterValue m_flags;
2743
2744 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2745 m_process(process), m_reg_context(reg_context) {}
2746};
2747
2748} // anonymous namespace
2749
2750static size_t
2751ReadMemoryCallback (EmulateInstruction *instruction,
2752 void *baton,
2753 const EmulateInstruction::Context &context,
2754 lldb::addr_t addr,
2755 void *dst,
2756 size_t length)
2757{
2758 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2759
2760 lldb::addr_t bytes_read;
2761 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2762 return bytes_read;
2763}
2764
2765static bool
2766ReadRegisterCallback (EmulateInstruction *instruction,
2767 void *baton,
2768 const RegisterInfo *reg_info,
2769 RegisterValue &reg_value)
2770{
2771 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2772
2773 // The emulator only fill in the dwarf regsiter numbers (and in some case
2774 // the generic register numbers). Get the full register info from the
2775 // register context based on the dwarf register numbers.
2776 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2777 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2778
2779 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
2780 return error.Success();
2781}
2782
2783static bool
2784WriteRegisterCallback (EmulateInstruction *instruction,
2785 void *baton,
2786 const EmulateInstruction::Context &context,
2787 const RegisterInfo *reg_info,
2788 const RegisterValue &reg_value)
2789{
2790 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2791
2792 switch (reg_info->kinds[eRegisterKindGeneric])
2793 {
2794 case LLDB_REGNUM_GENERIC_PC:
2795 emulator_baton->m_pc = reg_value;
2796 break;
2797 case LLDB_REGNUM_GENERIC_FLAGS:
2798 emulator_baton->m_flags = reg_value;
2799 break;
2800 }
2801
2802 return true;
2803}
2804
2805static size_t
2806WriteMemoryCallback (EmulateInstruction *instruction,
2807 void *baton,
2808 const EmulateInstruction::Context &context,
2809 lldb::addr_t addr,
2810 const void *dst,
2811 size_t length)
2812{
2813 return length;
2814}
2815
2816static lldb::addr_t
2817ReadFlags (NativeRegisterContext* regsiter_context)
2818{
2819 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2820 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2821 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2822}
2823
2824Error
2825NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2826{
2827 Error error;
2828 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2829
2830 std::unique_ptr<EmulateInstruction> emulator_ap(
2831 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2832
2833 if (emulator_ap == nullptr)
2834 return Error("Instruction emulator not found!");
2835
2836 EmulatorBaton baton(this, register_context_sp.get());
2837 emulator_ap->SetBaton(&baton);
2838 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2839 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2840 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2841 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2842
2843 if (!emulator_ap->ReadInstruction())
2844 return Error("Read instruction failed!");
2845
2846 lldb::addr_t next_pc;
2847 lldb::addr_t next_flags;
2848 if (emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC))
2849 {
2850 next_pc = baton.m_pc.GetAsUInt64();
2851 if (baton.m_flags.GetType() != RegisterValue::eTypeInvalid)
2852 next_flags = baton.m_flags.GetAsUInt32();
2853 else
2854 next_flags = ReadFlags (register_context_sp.get());
2855 }
2856 else if (baton.m_pc.GetType() == RegisterValue::eTypeInvalid)
2857 {
2858 // Emulate instruction failed and it haven't changed PC. Advance PC
2859 // with the size of the current opcode because the emulation of all
2860 // PC modifying instruction should be successful. The failure most
2861 // likely caused by a not supported instruction which don't modify PC.
2862 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2863 next_flags = ReadFlags (register_context_sp.get());
2864 }
2865 else
2866 {
2867 // The instruction emulation failed after it modified the PC. It is an
2868 // unknown error where we can't continue because the next instruction is
2869 // modifying the PC but we don't know how.
2870 return Error ("Instruction emulation failed unexpectedly.");
2871 }
2872
2873 if (m_arch.GetMachine() == llvm::Triple::arm)
2874 {
2875 if (next_flags & 0x20)
2876 {
2877 // Thumb mode
2878 error = SetSoftwareBreakpoint(next_pc, 2);
2879 }
2880 else
2881 {
2882 // Arm mode
2883 error = SetSoftwareBreakpoint(next_pc, 4);
2884 }
2885 }
2886 else
2887 {
2888 // No size hint is given for the next breakpoint
2889 error = SetSoftwareBreakpoint(next_pc, 0);
2890 }
2891
2892
2893 if (error.Fail())
2894 return error;
2895
2896 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2897
2898 return Error();
2899}
2900
2901bool
2902NativeProcessLinux::SupportHardwareSingleStepping() const
2903{
2904 return m_arch.GetMachine() != llvm::Triple::arm;
2905}
2906
Todd Fialaaf245d12014-06-30 21:05:18 +00002907Error
2908NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2909{
Todd Fialaaf245d12014-06-30 21:05:18 +00002910 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2911 if (log)
2912 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2913
Chaoren Lin03f12d62015-02-03 01:50:49 +00002914 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2915 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002916 int deferred_signo = 0;
2917 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002918 bool stepping = false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002919 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002920
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002921 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002922
Tamas Berghammere7708682015-04-22 10:00:23 +00002923 if (software_single_step)
2924 {
2925 for (auto thread_sp : m_threads)
2926 {
2927 assert (thread_sp && "thread list should not contain NULL threads");
2928
2929 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2930 if (action == nullptr)
2931 continue;
2932
2933 if (action->state == eStateStepping)
2934 {
2935 Error error = SetupSoftwareSingleStepping(thread_sp);
2936 if (error.Fail())
2937 return error;
2938 }
2939 }
2940 }
2941
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002942 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002943 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002944 assert (thread_sp && "thread list should not contain NULL threads");
2945
2946 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2947
2948 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002949 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002950 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002951 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2952 __FUNCTION__, GetID (), thread_sp->GetID ());
2953 continue;
2954 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002955
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002956 if (log)
2957 {
2958 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2959 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2960 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002961
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002962 switch (action->state)
2963 {
2964 case eStateRunning:
2965 {
2966 // Run the thread, possibly feeding it the signal.
2967 const int signo = action->signal;
2968 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2969 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2970 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002971 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002972 // Pass this signal number on to the inferior to handle.
2973 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2974 if (resume_result.Success())
2975 SetState(eStateRunning, true);
2976 return resume_result;
2977 },
2978 CoordinatorErrorHandler);
2979 break;
2980 }
2981
2982 case eStateStepping:
2983 {
2984 // Request the step.
2985 const int signo = action->signal;
2986 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2987 [=](lldb::tid_t tid_to_step, bool supress_signal)
2988 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002989 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002990
2991 Error step_result;
2992 if (software_single_step)
2993 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2994 else
2995 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2996
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002997 assert (step_result.Success() && "SingleStep() failed");
2998 if (step_result.Success())
2999 SetState(eStateStepping, true);
3000 return step_result;
3001 },
3002 CoordinatorErrorHandler);
3003 stepping = true;
3004 break;
3005 }
3006
3007 case eStateSuspended:
3008 case eStateStopped:
3009 // if we haven't chosen a deferred signal tid yet, use this one.
3010 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00003011 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003012 deferred_signal_tid = thread_sp->GetID ();
3013 deferred_signal_thread_sp = thread_sp;
3014 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00003015 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003016 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00003017
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003018 default:
3019 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3020 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003021 }
3022 }
3023
Chaoren Linfa03ad22015-02-03 01:50:42 +00003024 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
3025 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003026 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
3027 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00003028 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00003029 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
3030 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003031 [=](lldb::tid_t deferred_notification_tid)
3032 {
Chaoren Linae29d392015-02-03 01:50:46 +00003033 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00003034 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00003035
3036 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003037 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00003038
3039 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00003040 SetState (StateType::eStateStopped, true);
3041 });
Todd Fialaaf245d12014-06-30 21:05:18 +00003042 }
3043
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003044 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00003045}
3046
3047Error
3048NativeProcessLinux::Halt ()
3049{
3050 Error error;
3051
Todd Fialaaf245d12014-06-30 21:05:18 +00003052 if (kill (GetID (), SIGSTOP) != 0)
3053 error.SetErrorToErrno ();
3054
3055 return error;
3056}
3057
3058Error
3059NativeProcessLinux::Detach ()
3060{
3061 Error error;
3062
3063 // Tell ptrace to detach from the process.
3064 if (GetID () != LLDB_INVALID_PROCESS_ID)
3065 error = Detach (GetID ());
3066
3067 // Stop monitoring the inferior.
3068 StopMonitor ();
3069
3070 // No error.
3071 return error;
3072}
3073
3074Error
3075NativeProcessLinux::Signal (int signo)
3076{
3077 Error error;
3078
3079 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3080 if (log)
3081 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3082 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3083
3084 if (kill(GetID(), signo))
3085 error.SetErrorToErrno();
3086
3087 return error;
3088}
3089
3090Error
Chaoren Line9547b82015-02-03 01:51:00 +00003091NativeProcessLinux::Interrupt ()
3092{
3093 // Pick a running thread (or if none, a not-dead stopped thread) as
3094 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00003095 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3096
3097 NativeThreadProtocolSP running_thread_sp;
3098 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003099
3100 if (log)
3101 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3102
3103 Mutex::Locker locker (m_threads_mutex);
3104
3105 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00003106 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003107 // The thread shouldn't be null but lets just cover that here.
3108 if (!thread_sp)
3109 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00003110
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003111 // If we have a running or stepping thread, we'll call that the
3112 // target of the interrupt.
3113 const auto thread_state = thread_sp->GetState ();
3114 if (thread_state == eStateRunning ||
3115 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00003116 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003117 running_thread_sp = thread_sp;
3118 break;
3119 }
3120 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3121 {
3122 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
3123 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00003124 }
3125 }
3126
3127 if (!running_thread_sp && !stopped_thread_sp)
3128 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003129 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00003130 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00003131 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003132
Chaoren Line9547b82015-02-03 01:51:00 +00003133 return error;
3134 }
3135
3136 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3137
3138 if (log)
3139 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3140 __FUNCTION__,
3141 GetID (),
3142 running_thread_sp ? "running" : "stopped",
3143 deferred_signal_thread_sp->GetID ());
3144
3145 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
3146 [=](lldb::tid_t deferred_notification_tid)
3147 {
3148 // Set the signal thread to the current thread.
3149 SetCurrentThreadID (deferred_notification_tid);
3150
3151 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003152 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00003153
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003154 // Tell the process delegate that the process is in a stopped state.
3155 SetState (StateType::eStateStopped, true);
3156 });
3157 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00003158}
3159
3160Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003161NativeProcessLinux::Kill ()
3162{
3163 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3164 if (log)
3165 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3166
3167 Error error;
3168
3169 switch (m_state)
3170 {
3171 case StateType::eStateInvalid:
3172 case StateType::eStateExited:
3173 case StateType::eStateCrashed:
3174 case StateType::eStateDetached:
3175 case StateType::eStateUnloaded:
3176 // Nothing to do - the process is already dead.
3177 if (log)
3178 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3179 return error;
3180
3181 case StateType::eStateConnected:
3182 case StateType::eStateAttaching:
3183 case StateType::eStateLaunching:
3184 case StateType::eStateStopped:
3185 case StateType::eStateRunning:
3186 case StateType::eStateStepping:
3187 case StateType::eStateSuspended:
3188 // We can try to kill a process in these states.
3189 break;
3190 }
3191
3192 if (kill (GetID (), SIGKILL) != 0)
3193 {
3194 error.SetErrorToErrno ();
3195 return error;
3196 }
3197
3198 return error;
3199}
3200
3201static Error
3202ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3203{
3204 memory_region_info.Clear();
3205
3206 StringExtractor line_extractor (maps_line.c_str ());
3207
3208 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
3209 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
3210
3211 // Parse out the starting address
3212 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3213
3214 // Parse out hyphen separating start and end address from range.
3215 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3216 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3217
3218 // Parse out the ending address
3219 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3220
3221 // Parse out the space after the address.
3222 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3223 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3224
3225 // Save the range.
3226 memory_region_info.GetRange ().SetRangeBase (start_address);
3227 memory_region_info.GetRange ().SetRangeEnd (end_address);
3228
3229 // Parse out each permission entry.
3230 if (line_extractor.GetBytesLeft () < 4)
3231 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3232
3233 // Handle read permission.
3234 const char read_perm_char = line_extractor.GetChar ();
3235 if (read_perm_char == 'r')
3236 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3237 else
3238 {
3239 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3240 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3241 }
3242
3243 // Handle write permission.
3244 const char write_perm_char = line_extractor.GetChar ();
3245 if (write_perm_char == 'w')
3246 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3247 else
3248 {
3249 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3250 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3251 }
3252
3253 // Handle execute permission.
3254 const char exec_perm_char = line_extractor.GetChar ();
3255 if (exec_perm_char == 'x')
3256 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3257 else
3258 {
3259 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3260 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3261 }
3262
3263 return Error ();
3264}
3265
3266Error
3267NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3268{
3269 // FIXME review that the final memory region returned extends to the end of the virtual address space,
3270 // with no perms if it is not mapped.
3271
3272 // Use an approach that reads memory regions from /proc/{pid}/maps.
3273 // Assume proc maps entries are in ascending order.
3274 // FIXME assert if we find differently.
3275 Mutex::Locker locker (m_mem_region_cache_mutex);
3276
3277 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3278 Error error;
3279
3280 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3281 {
3282 // We're done.
3283 error.SetErrorString ("unsupported");
3284 return error;
3285 }
3286
3287 // If our cache is empty, pull the latest. There should always be at least one memory region
3288 // if memory region handling is supported.
3289 if (m_mem_region_cache.empty ())
3290 {
3291 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3292 [&] (const std::string &line) -> bool
3293 {
3294 MemoryRegionInfo info;
3295 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3296 if (parse_error.Success ())
3297 {
3298 m_mem_region_cache.push_back (info);
3299 return true;
3300 }
3301 else
3302 {
3303 if (log)
3304 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3305 return false;
3306 }
3307 });
3308
3309 // If we had an error, we'll mark unsupported.
3310 if (error.Fail ())
3311 {
3312 m_supports_mem_region = LazyBool::eLazyBoolNo;
3313 return error;
3314 }
3315 else if (m_mem_region_cache.empty ())
3316 {
3317 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3318 // is supported. Assume we don't support map entries via procfs.
3319 if (log)
3320 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3321 m_supports_mem_region = LazyBool::eLazyBoolNo;
3322 error.SetErrorString ("not supported");
3323 return error;
3324 }
3325
3326 if (log)
3327 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3328
3329 // We support memory retrieval, remember that.
3330 m_supports_mem_region = LazyBool::eLazyBoolYes;
3331 }
3332 else
3333 {
3334 if (log)
3335 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3336 }
3337
3338 lldb::addr_t prev_base_address = 0;
3339
3340 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3341 // There can be a ton of regions on pthreads apps with lots of threads.
3342 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3343 {
3344 MemoryRegionInfo &proc_entry_info = *it;
3345
3346 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3347 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3348 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3349
3350 // If the target address comes before this entry, indicate distance to next region.
3351 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3352 {
3353 range_info.GetRange ().SetRangeBase (load_addr);
3354 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3355 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3356 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3357 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3358
3359 return error;
3360 }
3361 else if (proc_entry_info.GetRange ().Contains (load_addr))
3362 {
3363 // The target address is within the memory region we're processing here.
3364 range_info = proc_entry_info;
3365 return error;
3366 }
3367
3368 // The target memory address comes somewhere after the region we just parsed.
3369 }
3370
3371 // If we made it here, we didn't find an entry that contained the given address.
3372 error.SetErrorString ("address comes after final region");
3373
3374 if (log)
3375 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3376
3377 return error;
3378}
3379
3380void
3381NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3382{
3383 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3384 if (log)
3385 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3386
3387 {
3388 Mutex::Locker locker (m_mem_region_cache_mutex);
3389 if (log)
3390 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3391 m_mem_region_cache.clear ();
3392 }
3393}
3394
3395Error
3396NativeProcessLinux::AllocateMemory (
3397 lldb::addr_t size,
3398 uint32_t permissions,
3399 lldb::addr_t &addr)
3400{
3401 // FIXME implementing this requires the equivalent of
3402 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3403 // functional ThreadPlans working with Native*Protocol.
3404#if 1
3405 return Error ("not implemented yet");
3406#else
3407 addr = LLDB_INVALID_ADDRESS;
3408
3409 unsigned prot = 0;
3410 if (permissions & lldb::ePermissionsReadable)
3411 prot |= eMmapProtRead;
3412 if (permissions & lldb::ePermissionsWritable)
3413 prot |= eMmapProtWrite;
3414 if (permissions & lldb::ePermissionsExecutable)
3415 prot |= eMmapProtExec;
3416
3417 // TODO implement this directly in NativeProcessLinux
3418 // (and lift to NativeProcessPOSIX if/when that class is
3419 // refactored out).
3420 if (InferiorCallMmap(this, addr, 0, size, prot,
3421 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3422 m_addr_to_mmap_size[addr] = size;
3423 return Error ();
3424 } else {
3425 addr = LLDB_INVALID_ADDRESS;
3426 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3427 }
3428#endif
3429}
3430
3431Error
3432NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3433{
3434 // FIXME see comments in AllocateMemory - required lower-level
3435 // bits not in place yet (ThreadPlans)
3436 return Error ("not implemented");
3437}
3438
3439lldb::addr_t
3440NativeProcessLinux::GetSharedLibraryInfoAddress ()
3441{
3442#if 1
3443 // punt on this for now
3444 return LLDB_INVALID_ADDRESS;
3445#else
3446 // Return the image info address for the exe module
3447#if 1
3448 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3449
3450 ModuleSP module_sp;
3451 Error error = GetExeModuleSP (module_sp);
3452 if (error.Fail ())
3453 {
3454 if (log)
3455 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3456 return LLDB_INVALID_ADDRESS;
3457 }
3458
3459 if (module_sp == nullptr)
3460 {
3461 if (log)
3462 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3463 return LLDB_INVALID_ADDRESS;
3464 }
3465
3466 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3467 if (object_file_sp == nullptr)
3468 {
3469 if (log)
3470 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3471 return LLDB_INVALID_ADDRESS;
3472 }
3473
3474 return obj_file_sp->GetImageInfoAddress();
3475#else
3476 Target *target = &GetTarget();
3477 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3478 Address addr = obj_file->GetImageInfoAddress(target);
3479
3480 if (addr.IsValid())
3481 return addr.GetLoadAddress(target);
3482 return LLDB_INVALID_ADDRESS;
3483#endif
3484#endif // punt on this for now
3485}
3486
3487size_t
3488NativeProcessLinux::UpdateThreads ()
3489{
3490 // The NativeProcessLinux monitoring threads are always up to date
3491 // with respect to thread state and they keep the thread list
3492 // populated properly. All this method needs to do is return the
3493 // thread count.
3494 Mutex::Locker locker (m_threads_mutex);
3495 return m_threads.size ();
3496}
3497
3498bool
3499NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3500{
3501 arch = m_arch;
3502 return true;
3503}
3504
3505Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003506NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003507{
3508 // FIXME put this behind a breakpoint protocol class that can be
3509 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003510 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003511 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003512 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003513
3514 switch (m_arch.GetMachine ())
3515 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003516 case llvm::Triple::aarch64:
3517 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3518 return Error ();
3519
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003520 case llvm::Triple::arm:
3521 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3522 return Error ();
3523
Todd Fialaaf245d12014-06-30 21:05:18 +00003524 case llvm::Triple::x86:
3525 case llvm::Triple::x86_64:
3526 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3527 return Error ();
3528
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003529 case llvm::Triple::mips64:
3530 case llvm::Triple::mips64el:
3531 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3532 return Error ();
3533
Todd Fialaaf245d12014-06-30 21:05:18 +00003534 default:
3535 assert(false && "CPU type not supported!");
3536 return Error ("CPU type not supported");
3537 }
3538}
3539
3540Error
3541NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3542{
3543 if (hardware)
3544 return Error ("NativeProcessLinux does not support hardware breakpoints");
3545 else
3546 return SetSoftwareBreakpoint (addr, size);
3547}
3548
3549Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003550NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3551 size_t &actual_opcode_size,
3552 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003553{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003554 // FIXME put this behind a breakpoint protocol class that can be set per
3555 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003556 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003557 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3558 // linux kernel does otherwise.
3559 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003560 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003561 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003562 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003563 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003564
3565 switch (m_arch.GetMachine ())
3566 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003567 case llvm::Triple::aarch64:
3568 trap_opcode_bytes = g_aarch64_opcode;
3569 actual_opcode_size = sizeof(g_aarch64_opcode);
3570 return Error ();
3571
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003572 case llvm::Triple::arm:
3573 switch (trap_opcode_size_hint)
3574 {
3575 case 2:
3576 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3577 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3578 return Error ();
3579 case 4:
3580 trap_opcode_bytes = g_arm_breakpoint_opcode;
3581 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3582 return Error ();
3583 default:
3584 assert(false && "Unrecognised trap opcode size hint!");
3585 return Error ("Unrecognised trap opcode size hint!");
3586 }
3587
Todd Fialaaf245d12014-06-30 21:05:18 +00003588 case llvm::Triple::x86:
3589 case llvm::Triple::x86_64:
3590 trap_opcode_bytes = g_i386_opcode;
3591 actual_opcode_size = sizeof(g_i386_opcode);
3592 return Error ();
3593
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003594 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003595 trap_opcode_bytes = g_mips64_opcode;
3596 actual_opcode_size = sizeof(g_mips64_opcode);
3597 return Error ();
3598
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003599 case llvm::Triple::mips64el:
3600 trap_opcode_bytes = g_mips64el_opcode;
3601 actual_opcode_size = sizeof(g_mips64el_opcode);
3602 return Error ();
3603
Todd Fialaaf245d12014-06-30 21:05:18 +00003604 default:
3605 assert(false && "CPU type not supported!");
3606 return Error ("CPU type not supported");
3607 }
3608}
3609
3610#if 0
3611ProcessMessage::CrashReason
3612NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3613{
3614 ProcessMessage::CrashReason reason;
3615 assert(info->si_signo == SIGSEGV);
3616
3617 reason = ProcessMessage::eInvalidCrashReason;
3618
3619 switch (info->si_code)
3620 {
3621 default:
3622 assert(false && "unexpected si_code for SIGSEGV");
3623 break;
3624 case SI_KERNEL:
3625 // Linux will occasionally send spurious SI_KERNEL codes.
3626 // (this is poorly documented in sigaction)
3627 // One way to get this is via unaligned SIMD loads.
3628 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3629 break;
3630 case SEGV_MAPERR:
3631 reason = ProcessMessage::eInvalidAddress;
3632 break;
3633 case SEGV_ACCERR:
3634 reason = ProcessMessage::ePrivilegedAddress;
3635 break;
3636 }
3637
3638 return reason;
3639}
3640#endif
3641
3642
3643#if 0
3644ProcessMessage::CrashReason
3645NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3646{
3647 ProcessMessage::CrashReason reason;
3648 assert(info->si_signo == SIGILL);
3649
3650 reason = ProcessMessage::eInvalidCrashReason;
3651
3652 switch (info->si_code)
3653 {
3654 default:
3655 assert(false && "unexpected si_code for SIGILL");
3656 break;
3657 case ILL_ILLOPC:
3658 reason = ProcessMessage::eIllegalOpcode;
3659 break;
3660 case ILL_ILLOPN:
3661 reason = ProcessMessage::eIllegalOperand;
3662 break;
3663 case ILL_ILLADR:
3664 reason = ProcessMessage::eIllegalAddressingMode;
3665 break;
3666 case ILL_ILLTRP:
3667 reason = ProcessMessage::eIllegalTrap;
3668 break;
3669 case ILL_PRVOPC:
3670 reason = ProcessMessage::ePrivilegedOpcode;
3671 break;
3672 case ILL_PRVREG:
3673 reason = ProcessMessage::ePrivilegedRegister;
3674 break;
3675 case ILL_COPROC:
3676 reason = ProcessMessage::eCoprocessorError;
3677 break;
3678 case ILL_BADSTK:
3679 reason = ProcessMessage::eInternalStackError;
3680 break;
3681 }
3682
3683 return reason;
3684}
3685#endif
3686
3687#if 0
3688ProcessMessage::CrashReason
3689NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3690{
3691 ProcessMessage::CrashReason reason;
3692 assert(info->si_signo == SIGFPE);
3693
3694 reason = ProcessMessage::eInvalidCrashReason;
3695
3696 switch (info->si_code)
3697 {
3698 default:
3699 assert(false && "unexpected si_code for SIGFPE");
3700 break;
3701 case FPE_INTDIV:
3702 reason = ProcessMessage::eIntegerDivideByZero;
3703 break;
3704 case FPE_INTOVF:
3705 reason = ProcessMessage::eIntegerOverflow;
3706 break;
3707 case FPE_FLTDIV:
3708 reason = ProcessMessage::eFloatDivideByZero;
3709 break;
3710 case FPE_FLTOVF:
3711 reason = ProcessMessage::eFloatOverflow;
3712 break;
3713 case FPE_FLTUND:
3714 reason = ProcessMessage::eFloatUnderflow;
3715 break;
3716 case FPE_FLTRES:
3717 reason = ProcessMessage::eFloatInexactResult;
3718 break;
3719 case FPE_FLTINV:
3720 reason = ProcessMessage::eFloatInvalidOperation;
3721 break;
3722 case FPE_FLTSUB:
3723 reason = ProcessMessage::eFloatSubscriptRange;
3724 break;
3725 }
3726
3727 return reason;
3728}
3729#endif
3730
3731#if 0
3732ProcessMessage::CrashReason
3733NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3734{
3735 ProcessMessage::CrashReason reason;
3736 assert(info->si_signo == SIGBUS);
3737
3738 reason = ProcessMessage::eInvalidCrashReason;
3739
3740 switch (info->si_code)
3741 {
3742 default:
3743 assert(false && "unexpected si_code for SIGBUS");
3744 break;
3745 case BUS_ADRALN:
3746 reason = ProcessMessage::eIllegalAlignment;
3747 break;
3748 case BUS_ADRERR:
3749 reason = ProcessMessage::eIllegalAddress;
3750 break;
3751 case BUS_OBJERR:
3752 reason = ProcessMessage::eHardwareError;
3753 break;
3754 }
3755
3756 return reason;
3757}
3758#endif
3759
Todd Fialaaf245d12014-06-30 21:05:18 +00003760Error
3761NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3762{
3763 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003764 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003765 return op.GetError ();
3766}
3767
3768Error
3769NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3770{
3771 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003772 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003773 return op.GetError ();
3774}
3775
Chaoren Lin97ccc292015-02-03 01:51:12 +00003776Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003777NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003778 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003779{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003780 ReadRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003781 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003782 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003783}
3784
Chaoren Lin97ccc292015-02-03 01:51:12 +00003785Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003786NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3787 const char* reg_name, const RegisterValue &value)
3788{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003789 WriteRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003790 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003791 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003792}
3793
Chaoren Lin97ccc292015-02-03 01:51:12 +00003794Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003795NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3796{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003797 ReadGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003798 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003799 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003800}
3801
Chaoren Lin97ccc292015-02-03 01:51:12 +00003802Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003803NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3804{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003805 ReadFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003806 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003807 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003808}
3809
Chaoren Lin97ccc292015-02-03 01:51:12 +00003810Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003811NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3812{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003813 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003814 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003815 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003816}
3817
Chaoren Lin97ccc292015-02-03 01:51:12 +00003818Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003819NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3820{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003821 WriteGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003822 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003823 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003824}
3825
Chaoren Lin97ccc292015-02-03 01:51:12 +00003826Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003827NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3828{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003829 WriteFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003830 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003831 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003832}
3833
Chaoren Lin97ccc292015-02-03 01:51:12 +00003834Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003835NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3836{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003837 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003838 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003839 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003840}
3841
Chaoren Lin97ccc292015-02-03 01:51:12 +00003842Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003843NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3844{
Todd Fialaaf245d12014-06-30 21:05:18 +00003845 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3846
3847 if (log)
3848 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3849 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003850 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003851 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003852 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003853 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3854 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003855}
3856
Chaoren Lin97ccc292015-02-03 01:51:12 +00003857Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003858NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3859{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003860 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003861 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003862 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003863}
3864
Chaoren Lin97ccc292015-02-03 01:51:12 +00003865Error
3866NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003867{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003868 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003869 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003870 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003871}
3872
Chaoren Lin97ccc292015-02-03 01:51:12 +00003873Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003874NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3875{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003876 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003877 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003878 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003879}
3880
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003881Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003882NativeProcessLinux::Detach(lldb::tid_t tid)
3883{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003884 if (tid == LLDB_INVALID_THREAD_ID)
3885 return Error();
3886
3887 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003888 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003889 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003890}
3891
3892bool
3893NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3894{
3895 int target_fd = open(path, flags, 0666);
3896
3897 if (target_fd == -1)
3898 return false;
3899
Pavel Labath493c3a12015-02-04 10:36:57 +00003900 if (dup2(target_fd, fd) == -1)
3901 return false;
3902
3903 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003904}
3905
3906void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003907NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003908{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003909 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003910 error = m_monitor_up->Initialize();
3911 if (error.Fail()) {
3912 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003913 }
3914}
3915
3916void
3917NativeProcessLinux::StopMonitor()
3918{
Chaoren Linfa03ad22015-02-03 01:50:42 +00003919 StopCoordinatorThread ();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003920 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003921}
3922
Chaoren Linfa03ad22015-02-03 01:50:42 +00003923Error
3924NativeProcessLinux::StartCoordinatorThread ()
3925{
3926 Error error;
3927 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3928 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3929
3930 // Skip if thread is already running
3931 if (m_coordinator_thread.IsJoinable())
3932 {
3933 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3934 if (log)
3935 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3936 return error;
3937 }
3938
3939 // Enable verbose logging if lldb thread logging is enabled.
3940 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3941
3942 if (log)
3943 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3944 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3945 return error;
3946}
3947
3948void *
3949NativeProcessLinux::CoordinatorThread (void *arg)
3950{
3951 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3952
3953 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3954 assert (process && "null process passed to CoordinatorThread");
3955 if (!process)
3956 {
3957 if (log)
3958 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3959 return nullptr;
3960 }
3961
3962 // Run the thread state coordinator loop until it is done. This call uses
3963 // efficient waiting for an event to be ready.
3964 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3965 {
3966 }
3967
3968 if (log)
3969 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3970
3971 return nullptr;
3972}
3973
3974void
3975NativeProcessLinux::StopCoordinatorThread()
3976{
3977 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3978 if (log)
3979 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3980
3981 // Tell the coordinator we're done. This will cause the coordinator
3982 // run loop thread to exit when the processing queue hits this message.
3983 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003984 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003985}
3986
Todd Fialaaf245d12014-06-30 21:05:18 +00003987bool
3988NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3989{
3990 for (auto thread_sp : m_threads)
3991 {
3992 assert (thread_sp && "thread list should not contain NULL threads");
3993 if (thread_sp->GetID () == thread_id)
3994 {
3995 // We have this thread.
3996 return true;
3997 }
3998 }
3999
4000 // We don't have this thread.
4001 return false;
4002}
4003
4004NativeThreadProtocolSP
4005NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4006{
4007 // CONSIDER organize threads by map - we can do better than linear.
4008 for (auto thread_sp : m_threads)
4009 {
4010 if (thread_sp->GetID () == thread_id)
4011 return thread_sp;
4012 }
4013
4014 // We don't have this thread.
4015 return NativeThreadProtocolSP ();
4016}
4017
4018bool
4019NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4020{
4021 Mutex::Locker locker (m_threads_mutex);
4022 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4023 {
4024 if (*it && ((*it)->GetID () == thread_id))
4025 {
4026 m_threads.erase (it);
4027 return true;
4028 }
4029 }
4030
4031 // Didn't find it.
4032 return false;
4033}
4034
4035NativeThreadProtocolSP
4036NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4037{
4038 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4039
4040 Mutex::Locker locker (m_threads_mutex);
4041
4042 if (log)
4043 {
4044 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4045 __FUNCTION__,
4046 GetID (),
4047 thread_id);
4048 }
4049
4050 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4051
4052 // If this is the first thread, save it as the current thread
4053 if (m_threads.empty ())
4054 SetCurrentThreadID (thread_id);
4055
4056 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4057 m_threads.push_back (thread_sp);
4058
4059 return thread_sp;
4060}
4061
Todd Fialaaf245d12014-06-30 21:05:18 +00004062Error
4063NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4064{
Todd Fiala75f47c32014-10-11 21:42:09 +00004065 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00004066
4067 Error error;
4068
4069 // Get a linux thread pointer.
4070 if (!thread_sp)
4071 {
4072 error.SetErrorString ("null thread_sp");
4073 if (log)
4074 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4075 return error;
4076 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004077 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00004078
4079 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004080 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00004081 if (!context_sp)
4082 {
4083 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4084 if (log)
4085 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4086 return error;
4087 }
4088
4089 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00004090 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00004091 if (error.Fail ())
4092 {
4093 if (log)
4094 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4095 return error;
4096 }
4097 else
4098 {
4099 if (log)
4100 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4101 }
4102
4103 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4104 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4105 lldb::addr_t breakpoint_addr = initial_pc_addr;
4106 if (breakpoint_size > static_cast<lldb::addr_t> (0))
4107 {
4108 // Do not allow breakpoint probe to wrap around.
4109 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
4110 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
4111 }
4112
4113 // Check if we stopped because of a breakpoint.
4114 NativeBreakpointSP breakpoint_sp;
4115 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4116 if (!error.Success () || !breakpoint_sp)
4117 {
4118 // We didn't find one at a software probe location. Nothing to do.
4119 if (log)
4120 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4121 return Error ();
4122 }
4123
4124 // If the breakpoint is not a software breakpoint, nothing to do.
4125 if (!breakpoint_sp->IsSoftwareBreakpoint ())
4126 {
4127 if (log)
4128 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4129 return Error ();
4130 }
4131
4132 //
4133 // We have a software breakpoint and need to adjust the PC.
4134 //
4135
4136 // Sanity check.
4137 if (breakpoint_size == 0)
4138 {
4139 // Nothing to do! How did we get here?
4140 if (log)
4141 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);
4142 return Error ();
4143 }
4144
4145 // Change the program counter.
4146 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004147 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 +00004148
4149 error = context_sp->SetPC (breakpoint_addr);
4150 if (error.Fail ())
4151 {
4152 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004153 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 +00004154 return error;
4155 }
4156
4157 return error;
4158}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004159
4160void
4161NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
4162{
4163 const bool is_stopped = true;
4164 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
4165}
4166
4167void
4168NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
4169{
4170 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
4171}
4172
4173void
4174NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
4175{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004176 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004177}
4178
4179void
4180NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
4181 const std::function<void (lldb::tid_t tid)> &call_after_function)
4182{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004183 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4184 if (log)
4185 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
4186
Chaoren Linfa03ad22015-02-03 01:50:42 +00004187 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00004188 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00004189 [=](lldb::tid_t request_stop_tid)
4190 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00004191 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004192 },
4193 call_after_function,
4194 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00004195}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004196
Chaoren Lin03f12d62015-02-03 01:50:49 +00004197void
4198NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
4199 lldb::tid_t skip_stop_request_tid,
4200 const std::function<void (lldb::tid_t tid)> &call_after_function)
4201{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004202 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4203 if (log)
4204 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
4205
Chaoren Lin03f12d62015-02-03 01:50:49 +00004206 const lldb::pid_t pid = GetID ();
4207 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
4208 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
4209 [=](lldb::tid_t request_stop_tid)
4210 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00004211 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00004212 },
4213 call_after_function,
4214 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004215}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004216
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004217Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004218NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
4219{
4220 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4221 if (log)
4222 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
4223
4224 Error err;
4225 errno = 0;
4226 if (::tgkill (pid, tid, SIGSTOP) != 0)
4227 {
4228 err.SetErrorToErrno ();
4229 if (log)
4230 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
4231 }
4232
4233 return err;
4234}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004235
4236Error
4237NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4238{
4239 char maps_file_name[32];
4240 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4241
4242 FileSpec maps_file_spec(maps_file_name, false);
4243 if (!maps_file_spec.Exists()) {
4244 file_spec.Clear();
4245 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4246 }
4247
4248 FileSpec module_file_spec(module_path, true);
4249
4250 std::ifstream maps_file(maps_file_name);
4251 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4252 StringRef maps_data(maps_data_str.c_str());
4253
4254 while (!maps_data.empty())
4255 {
4256 StringRef maps_row;
4257 std::tie(maps_row, maps_data) = maps_data.split('\n');
4258
4259 SmallVector<StringRef, 16> maps_columns;
4260 maps_row.split(maps_columns, StringRef(" "), -1, false);
4261
4262 if (maps_columns.size() >= 6)
4263 {
4264 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4265 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4266 return Error();
4267 }
4268 }
4269
4270 file_spec.Clear();
4271 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4272 module_file_spec.GetFilename().AsCString(), GetID());
4273}