blob: 0dfee5ef4736e45adb2c06ae260bfb19b387e65b [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
21// C++ Includes
22#include <fstream>
23#include <string>
24
25// Other libraries and framework includes
26#include "lldb/Core/Debugger.h"
27#include "lldb/Core/Error.h"
28#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000029#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/RegisterValue.h"
31#include "lldb/Core/Scalar.h"
32#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000033#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000034#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000035#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000036#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000037#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000038#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000042#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Utility/PseudoTerminal.h"
44
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000045#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000046#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000048#include "NativeThreadLinux.h"
49#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000050#include "Procfs.h"
Chaoren Linfa03ad22015-02-03 01:50:42 +000051#include "ThreadStateCoordinator.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000052
Tamas Berghammerd8584872015-02-06 10:57:40 +000053// System includes - They have to be included after framework includes because they define some
54// macros which collide with variable names in other modules
55#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000056#include <sys/personality.h>
57#include <sys/ptrace.h>
58#include <sys/socket.h>
59#include <sys/syscall.h>
60#include <sys/types.h>
61#include <sys/uio.h>
62#include <sys/user.h>
63#include <sys/wait.h>
64
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000065#if defined (__arm64__) || defined (__aarch64__)
66// NT_PRSTATUS and NT_FPREGSET definition
67#include <elf.h>
68#endif
69
Todd Fialacacde7d2014-09-27 16:54:22 +000070#ifdef __ANDROID__
71#define __ptrace_request int
72#define PT_DETACH PTRACE_DETACH
73#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000074
75#define DEBUG_PTRACE_MAXBYTES 20
76
77// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000078#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000079#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000080 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000081#endif
Todd Fialadda61942014-07-02 21:34:04 +000082#endif
83#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000084#ifndef PTRACE_SETREGS
85 #define PTRACE_SETREGS 13
86#endif
Todd Fialadda61942014-07-02 21:34:04 +000087#endif
88#ifndef PT_GETFPREGS
89#ifndef PTRACE_GETFPREGS
90 #define PTRACE_GETFPREGS 14
91#endif
92#endif
93#ifndef PT_SETFPREGS
94#ifndef PTRACE_SETFPREGS
95 #define PTRACE_SETFPREGS 15
96#endif
97#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000098#ifndef PTRACE_GETREGSET
99 #define PTRACE_GETREGSET 0x4204
100#endif
101#ifndef PTRACE_SETREGSET
102 #define PTRACE_SETREGSET 0x4205
103#endif
104#ifndef PTRACE_GET_THREAD_AREA
105 #define PTRACE_GET_THREAD_AREA 25
106#endif
107#ifndef PTRACE_ARCH_PRCTL
108 #define PTRACE_ARCH_PRCTL 30
109#endif
110#ifndef ARCH_GET_FS
111 #define ARCH_SET_GS 0x1001
112 #define ARCH_SET_FS 0x1002
113 #define ARCH_GET_FS 0x1003
114 #define ARCH_GET_GS 0x1004
115#endif
116
Todd Fiala0bce1b62014-08-17 00:10:50 +0000117#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000118
119// Support hardware breakpoints in case it has not been defined
120#ifndef TRAP_HWBKPT
121 #define TRAP_HWBKPT 4
122#endif
123
124// Try to define a macro to encapsulate the tgkill syscall
125// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000126#define tgkill(pid, tid, sig) \
127 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000128
129// We disable the tracing of ptrace calls for integration builds to
130// avoid the additional indirection and checks.
131#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000132#define PTRACE(req, pid, addr, data, data_size, error) \
133 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000134#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000135#define PTRACE(req, pid, addr, data, data_size, error) \
136 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000137#endif
138
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000139using namespace lldb;
140using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000141using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000142using namespace llvm;
143
Todd Fialaaf245d12014-06-30 21:05:18 +0000144// Private bits we only need internally.
145namespace
146{
Tamas Berghammer43f2d972015-03-04 11:10:03 +0000147 static void * const EXIT_OPERATION = nullptr;
148
Todd Fialaaf245d12014-06-30 21:05:18 +0000149 const UnixSignals&
150 GetUnixSignals ()
151 {
152 static process_linux::LinuxSignals signals;
153 return signals;
154 }
155
Chaoren Linfa03ad22015-02-03 01:50:42 +0000156 ThreadStateCoordinator::LogFunction
157 GetThreadLoggerFunction ()
158 {
159 return [](const char *format, va_list args)
160 {
161 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
162 if (log)
163 log->VAPrintf (format, args);
164 };
165 }
166
167 void
168 CoordinatorErrorHandler (const std::string &error_message)
169 {
170 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
171 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000172 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000173 assert (false && "ThreadStateCoordinator error reported");
174 }
175
Todd Fialaaf245d12014-06-30 21:05:18 +0000176 Error
177 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
178 {
179 // Grab process info for the running process.
180 ProcessInstanceInfo process_info;
181 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000182 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000183
184 // Resolve the executable module.
185 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000186 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000187 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
188 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000189 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000190 exe_module_sp,
191 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
192
193 if (!error.Success ())
194 return error;
195
196 // Check if we've got our architecture from the exe_module.
197 arch = exe_module_sp->GetArchitecture ();
198 if (arch.IsValid ())
199 return Error();
200 else
201 return Error("failed to retrieve a valid architecture from the exe module");
202 }
203
204 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000205 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000206 {
207 uint8_t *ptr = (uint8_t *)bytes;
208 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
209 for(uint32_t i=0; i<loop_count; i++)
210 {
211 s.Printf ("[%x]", *ptr);
212 ptr++;
213 }
214 }
215
216 void
217 PtraceDisplayBytes(int &req, void *data, size_t data_size)
218 {
219 StreamString buf;
220 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
221 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
222
223 if (verbose_log)
224 {
225 switch(req)
226 {
227 case PTRACE_POKETEXT:
228 {
229 DisplayBytes(buf, &data, 8);
230 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
231 break;
232 }
233 case PTRACE_POKEDATA:
234 {
235 DisplayBytes(buf, &data, 8);
236 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
237 break;
238 }
239 case PTRACE_POKEUSER:
240 {
241 DisplayBytes(buf, &data, 8);
242 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
243 break;
244 }
245 case PTRACE_SETREGS:
246 {
247 DisplayBytes(buf, data, data_size);
248 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
249 break;
250 }
251 case PTRACE_SETFPREGS:
252 {
253 DisplayBytes(buf, data, data_size);
254 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
255 break;
256 }
257 case PTRACE_SETSIGINFO:
258 {
259 DisplayBytes(buf, data, sizeof(siginfo_t));
260 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
261 break;
262 }
263 case PTRACE_SETREGSET:
264 {
265 // Extract iov_base from data, which is a pointer to the struct IOVEC
266 DisplayBytes(buf, *(void **)data, data_size);
267 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
268 break;
269 }
270 default:
271 {
272 }
273 }
274 }
275 }
276
277 // Wrapper for ptrace to catch errors and log calls.
278 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
279 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000280 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
281 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000282 {
283 long int result;
284
285 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
286
287 PtraceDisplayBytes(req, data, data_size);
288
Chaoren Lin97ccc292015-02-03 01:51:12 +0000289 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 errno = 0;
291 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000292 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000293 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000294 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000295
Chaoren Lin97ccc292015-02-03 01:51:12 +0000296 if (result == -1)
297 error.SetErrorToErrno();
298
Todd Fialaaf245d12014-06-30 21:05:18 +0000299 if (log)
300 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
301 reqName, pid, addr, data, data_size, result, file, line);
302
303 PtraceDisplayBytes(req, data, data_size);
304
Chaoren Lin97ccc292015-02-03 01:51:12 +0000305 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 {
307 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000308 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000309 {
310 case ESRCH: str = "ESRCH"; break;
311 case EINVAL: str = "EINVAL"; break;
312 case EBUSY: str = "EBUSY"; break;
313 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000314 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000315 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000316 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000317 }
318
319 return result;
320 }
321
322#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
323 // Wrapper for ptrace when logging is not required.
324 // Sets errno to 0 prior to calling ptrace.
325 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000326 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000327 {
328 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000329
330 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 errno = 0;
332 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000333 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000335 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000336
337 if (result == -1)
338 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000339 return result;
340 }
341#endif
342
343 //------------------------------------------------------------------------------
344 // Static implementations of NativeProcessLinux::ReadMemory and
345 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
346 // functions without needed to go thru the thread funnel.
347
Chaoren Lin97ccc292015-02-03 01:51:12 +0000348 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000349 DoReadMemory (
350 lldb::pid_t pid,
351 lldb::addr_t vm_addr,
352 void *buf,
353 lldb::addr_t size,
354 Error &error)
355 {
356 // ptrace word size is determined by the host, not the child
357 static const unsigned word_size = sizeof(void*);
358 unsigned char *dst = static_cast<unsigned char*>(buf);
359 lldb::addr_t bytes_read;
360 lldb::addr_t remainder;
361 long data;
362
363 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
364 if (log)
365 ProcessPOSIXLog::IncNestLevel();
366 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
367 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
368 pid, word_size, (void*)vm_addr, buf, size);
369
370 assert(sizeof(data) >= word_size);
371 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
372 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000373 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
374 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000376 if (log)
377 ProcessPOSIXLog::DecNestLevel();
378 return bytes_read;
379 }
380
381 remainder = size - bytes_read;
382 remainder = remainder > word_size ? word_size : remainder;
383
384 // Copy the data into our buffer
385 for (unsigned i = 0; i < remainder; ++i)
386 dst[i] = ((data >> i*8) & 0xFF);
387
388 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
389 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
390 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
391 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
392 {
393 uintptr_t print_dst = 0;
394 // Format bytes from data by moving into print_dst for log output
395 for (unsigned i = 0; i < remainder; ++i)
396 print_dst |= (((data >> i*8) & 0xFF) << i*8);
397 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
398 (void*)vm_addr, print_dst, (unsigned long)data);
399 }
400
401 vm_addr += word_size;
402 dst += word_size;
403 }
404
405 if (log)
406 ProcessPOSIXLog::DecNestLevel();
407 return bytes_read;
408 }
409
Chaoren Lin97ccc292015-02-03 01:51:12 +0000410 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000411 DoWriteMemory(
412 lldb::pid_t pid,
413 lldb::addr_t vm_addr,
414 const void *buf,
415 lldb::addr_t size,
416 Error &error)
417 {
418 // ptrace word size is determined by the host, not the child
419 static const unsigned word_size = sizeof(void*);
420 const unsigned char *src = static_cast<const unsigned char*>(buf);
421 lldb::addr_t bytes_written = 0;
422 lldb::addr_t remainder;
423
424 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
425 if (log)
426 ProcessPOSIXLog::IncNestLevel();
427 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
428 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
429 pid, word_size, (void*)vm_addr, buf, size);
430
431 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
432 {
433 remainder = size - bytes_written;
434 remainder = remainder > word_size ? word_size : remainder;
435
436 if (remainder == word_size)
437 {
438 unsigned long data = 0;
439 assert(sizeof(data) >= word_size);
440 for (unsigned i = 0; i < word_size; ++i)
441 data |= (unsigned long)src[i] << i*8;
442
443 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
446 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
447 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000448 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000449
Chaoren Lin97ccc292015-02-03 01:51:12 +0000450 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000451 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 if (log)
453 ProcessPOSIXLog::DecNestLevel();
454 return bytes_written;
455 }
456 }
457 else
458 {
459 unsigned char buff[8];
460 if (DoReadMemory(pid, vm_addr,
461 buff, word_size, error) != word_size)
462 {
463 if (log)
464 ProcessPOSIXLog::DecNestLevel();
465 return bytes_written;
466 }
467
468 memcpy(buff, src, remainder);
469
470 if (DoWriteMemory(pid, vm_addr,
471 buff, word_size, error) != word_size)
472 {
473 if (log)
474 ProcessPOSIXLog::DecNestLevel();
475 return bytes_written;
476 }
477
478 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
479 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
480 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
481 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
482 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000483 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 }
485
486 vm_addr += word_size;
487 src += word_size;
488 }
489 if (log)
490 ProcessPOSIXLog::DecNestLevel();
491 return bytes_written;
492 }
493
494 //------------------------------------------------------------------------------
495 /// @class Operation
496 /// @brief Represents a NativeProcessLinux operation.
497 ///
498 /// Under Linux, it is not possible to ptrace() from any other thread but the
499 /// one that spawned or attached to the process from the start. Therefore, when
500 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
501 /// process the operation must be "funneled" to a specific thread to perform the
502 /// task. The Operation class provides an abstract base for all services the
503 /// NativeProcessLinux must perform via the single virtual function Execute, thus
504 /// encapsulating the code that needs to run in the privileged context.
505 class Operation
506 {
507 public:
508 Operation () : m_error() { }
509
510 virtual
511 ~Operation() {}
512
513 virtual void
514 Execute (NativeProcessLinux *process) = 0;
515
516 const Error &
517 GetError () const { return m_error; }
518
519 protected:
520 Error m_error;
521 };
522
523 //------------------------------------------------------------------------------
524 /// @class ReadOperation
525 /// @brief Implements NativeProcessLinux::ReadMemory.
526 class ReadOperation : public Operation
527 {
528 public:
529 ReadOperation (
530 lldb::addr_t addr,
531 void *buff,
532 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000533 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000534 Operation (),
535 m_addr (addr),
536 m_buff (buff),
537 m_size (size),
538 m_result (result)
539 {
540 }
541
542 void Execute (NativeProcessLinux *process) override;
543
544 private:
545 lldb::addr_t m_addr;
546 void *m_buff;
547 lldb::addr_t m_size;
548 lldb::addr_t &m_result;
549 };
550
551 void
552 ReadOperation::Execute (NativeProcessLinux *process)
553 {
554 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
555 }
556
557 //------------------------------------------------------------------------------
558 /// @class WriteOperation
559 /// @brief Implements NativeProcessLinux::WriteMemory.
560 class WriteOperation : public Operation
561 {
562 public:
563 WriteOperation (
564 lldb::addr_t addr,
565 const void *buff,
566 lldb::addr_t size,
567 lldb::addr_t &result) :
568 Operation (),
569 m_addr (addr),
570 m_buff (buff),
571 m_size (size),
572 m_result (result)
573 {
574 }
575
576 void Execute (NativeProcessLinux *process) override;
577
578 private:
579 lldb::addr_t m_addr;
580 const void *m_buff;
581 lldb::addr_t m_size;
582 lldb::addr_t &m_result;
583 };
584
585 void
586 WriteOperation::Execute(NativeProcessLinux *process)
587 {
588 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
589 }
590
591 //------------------------------------------------------------------------------
592 /// @class ReadRegOperation
593 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
594 class ReadRegOperation : public Operation
595 {
596 public:
597 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000598 RegisterValue &value)
599 : m_tid(tid),
600 m_offset(static_cast<uintptr_t> (offset)),
601 m_reg_name(reg_name),
602 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000603 { }
604
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000605 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000606
607 private:
608 lldb::tid_t m_tid;
609 uintptr_t m_offset;
610 const char *m_reg_name;
611 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 };
613
614 void
615 ReadRegOperation::Execute(NativeProcessLinux *monitor)
616 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000617#if defined (__arm64__) || defined (__aarch64__)
618 if (m_offset > sizeof(struct user_pt_regs))
619 {
620 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
621 if (offset > sizeof(struct user_fpsimd_state))
622 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000623 m_error.SetErrorString("invalid offset value");
624 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000625 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000626 elf_fpregset_t regs;
627 int regset = NT_FPREGSET;
628 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000629
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 ioVec.iov_base = &regs;
631 ioVec.iov_len = sizeof regs;
632 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
633 if (m_error.Success())
634 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000635 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000636 if (monitor->GetArchitecture(arch))
637 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000638 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000639 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000640 }
641 }
642 else
643 {
644 elf_gregset_t regs;
645 int regset = NT_PRSTATUS;
646 struct iovec ioVec;
647
648 ioVec.iov_base = &regs;
649 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000650 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
651 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000652 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000653 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000654 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000656 else
657 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000658 }
659 }
660#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000661 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
662
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000663 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 +0000664 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000665 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000666
Todd Fialaaf245d12014-06-30 21:05:18 +0000667 if (log)
668 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
669 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000670#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000671 }
672
673 //------------------------------------------------------------------------------
674 /// @class WriteRegOperation
675 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
676 class WriteRegOperation : public Operation
677 {
678 public:
679 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000680 const RegisterValue &value)
681 : m_tid(tid),
682 m_offset(offset),
683 m_reg_name(reg_name),
684 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 { }
686
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000687 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000688
689 private:
690 lldb::tid_t m_tid;
691 uintptr_t m_offset;
692 const char *m_reg_name;
693 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000694 };
695
696 void
697 WriteRegOperation::Execute(NativeProcessLinux *monitor)
698 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000699#if defined (__arm64__) || defined (__aarch64__)
700 if (m_offset > sizeof(struct user_pt_regs))
701 {
702 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
703 if (offset > sizeof(struct user_fpsimd_state))
704 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000705 m_error.SetErrorString("invalid offset value");
706 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000707 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000708 elf_fpregset_t regs;
709 int regset = NT_FPREGSET;
710 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000711
Chaoren Lin97ccc292015-02-03 01:51:12 +0000712 ioVec.iov_base = &regs;
713 ioVec.iov_len = sizeof regs;
714 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000715 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000716 {
717 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
718 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000719 }
720 }
721 else
722 {
723 elf_gregset_t regs;
724 int regset = NT_PRSTATUS;
725 struct iovec ioVec;
726
727 ioVec.iov_base = &regs;
728 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000729 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000730 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000731 {
732 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000733 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000734 }
735 }
736#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000737 void* buf;
738 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
739
740 buf = (void*) m_value.GetAsUInt64();
741
742 if (log)
743 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000744 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000745#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000746 }
747
748 //------------------------------------------------------------------------------
749 /// @class ReadGPROperation
750 /// @brief Implements NativeProcessLinux::ReadGPR.
751 class ReadGPROperation : public Operation
752 {
753 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000754 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
755 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 { }
757
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000758 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000759
760 private:
761 lldb::tid_t m_tid;
762 void *m_buf;
763 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000764 };
765
766 void
767 ReadGPROperation::Execute(NativeProcessLinux *monitor)
768 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000769#if defined (__arm64__) || defined (__aarch64__)
770 int regset = NT_PRSTATUS;
771 struct iovec ioVec;
772
773 ioVec.iov_base = m_buf;
774 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000775 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000776#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000777 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000778#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000779 }
780
781 //------------------------------------------------------------------------------
782 /// @class ReadFPROperation
783 /// @brief Implements NativeProcessLinux::ReadFPR.
784 class ReadFPROperation : public Operation
785 {
786 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000787 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
788 : m_tid(tid),
789 m_buf(buf),
790 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000791 { }
792
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000793 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000794
795 private:
796 lldb::tid_t m_tid;
797 void *m_buf;
798 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000799 };
800
801 void
802 ReadFPROperation::Execute(NativeProcessLinux *monitor)
803 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000804#if defined (__arm64__) || defined (__aarch64__)
805 int regset = NT_FPREGSET;
806 struct iovec ioVec;
807
808 ioVec.iov_base = m_buf;
809 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000810 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000811#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000812 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000813#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000814 }
815
816 //------------------------------------------------------------------------------
817 /// @class ReadRegisterSetOperation
818 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
819 class ReadRegisterSetOperation : public Operation
820 {
821 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000822 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
823 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000824 { }
825
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000826 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000827
828 private:
829 lldb::tid_t m_tid;
830 void *m_buf;
831 size_t m_buf_size;
832 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 };
834
835 void
836 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
837 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000838 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000839 }
840
841 //------------------------------------------------------------------------------
842 /// @class WriteGPROperation
843 /// @brief Implements NativeProcessLinux::WriteGPR.
844 class WriteGPROperation : public Operation
845 {
846 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000847 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
848 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000849 { }
850
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000851 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000852
853 private:
854 lldb::tid_t m_tid;
855 void *m_buf;
856 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000857 };
858
859 void
860 WriteGPROperation::Execute(NativeProcessLinux *monitor)
861 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000862#if defined (__arm64__) || defined (__aarch64__)
863 int regset = NT_PRSTATUS;
864 struct iovec ioVec;
865
866 ioVec.iov_base = m_buf;
867 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000868 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000869#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000870 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000871#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000872 }
873
874 //------------------------------------------------------------------------------
875 /// @class WriteFPROperation
876 /// @brief Implements NativeProcessLinux::WriteFPR.
877 class WriteFPROperation : public Operation
878 {
879 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000880 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
881 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000882 { }
883
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000884 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000885
886 private:
887 lldb::tid_t m_tid;
888 void *m_buf;
889 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000890 };
891
892 void
893 WriteFPROperation::Execute(NativeProcessLinux *monitor)
894 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000895#if defined (__arm64__) || defined (__aarch64__)
896 int regset = NT_FPREGSET;
897 struct iovec ioVec;
898
899 ioVec.iov_base = m_buf;
900 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000901 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000902#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000903 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000904#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000905 }
906
907 //------------------------------------------------------------------------------
908 /// @class WriteRegisterSetOperation
909 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
910 class WriteRegisterSetOperation : public Operation
911 {
912 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000913 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
914 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000915 { }
916
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000917 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000918
919 private:
920 lldb::tid_t m_tid;
921 void *m_buf;
922 size_t m_buf_size;
923 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 };
925
926 void
927 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
928 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000929 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000930 }
931
932 //------------------------------------------------------------------------------
933 /// @class ResumeOperation
934 /// @brief Implements NativeProcessLinux::Resume.
935 class ResumeOperation : public Operation
936 {
937 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000938 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
939 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000940
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000941 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000942
943 private:
944 lldb::tid_t m_tid;
945 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000946 };
947
948 void
949 ResumeOperation::Execute(NativeProcessLinux *monitor)
950 {
951 intptr_t data = 0;
952
953 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
954 data = m_signo;
955
Chaoren Lin97ccc292015-02-03 01:51:12 +0000956 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
957 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000958 {
959 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
960
961 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000962 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000964 }
965
966 //------------------------------------------------------------------------------
967 /// @class SingleStepOperation
968 /// @brief Implements NativeProcessLinux::SingleStep.
969 class SingleStepOperation : public Operation
970 {
971 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000972 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
973 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000974
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000975 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000976
977 private:
978 lldb::tid_t m_tid;
979 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000980 };
981
982 void
983 SingleStepOperation::Execute(NativeProcessLinux *monitor)
984 {
985 intptr_t data = 0;
986
987 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
988 data = m_signo;
989
Chaoren Lin97ccc292015-02-03 01:51:12 +0000990 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000991 }
992
993 //------------------------------------------------------------------------------
994 /// @class SiginfoOperation
995 /// @brief Implements NativeProcessLinux::GetSignalInfo.
996 class SiginfoOperation : public Operation
997 {
998 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000999 SiginfoOperation(lldb::tid_t tid, void *info)
1000 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001001
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001002 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001003
1004 private:
1005 lldb::tid_t m_tid;
1006 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001007 };
1008
1009 void
1010 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1011 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001012 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001013 }
1014
1015 //------------------------------------------------------------------------------
1016 /// @class EventMessageOperation
1017 /// @brief Implements NativeProcessLinux::GetEventMessage.
1018 class EventMessageOperation : public Operation
1019 {
1020 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001021 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1022 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001023
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001024 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001025
1026 private:
1027 lldb::tid_t m_tid;
1028 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001029 };
1030
1031 void
1032 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1033 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001034 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001035 }
1036
1037 class DetachOperation : public Operation
1038 {
1039 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001040 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001041
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001042 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
1044 private:
1045 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001046 };
1047
1048 void
1049 DetachOperation::Execute(NativeProcessLinux *monitor)
1050 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001051 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001052 }
1053
1054}
1055
Todd Fialaaf245d12014-06-30 21:05:18 +00001056// Simple helper function to ensure flags are enabled on the given file
1057// descriptor.
1058static bool
1059EnsureFDFlags(int fd, int flags, Error &error)
1060{
1061 int status;
1062
1063 if ((status = fcntl(fd, F_GETFL)) == -1)
1064 {
1065 error.SetErrorToErrno();
1066 return false;
1067 }
1068
1069 if (fcntl(fd, F_SETFL, status | flags) == -1)
1070 {
1071 error.SetErrorToErrno();
1072 return false;
1073 }
1074
1075 return true;
1076}
1077
1078NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1079 : m_monitor(monitor)
1080{
1081 sem_init(&m_semaphore, 0, 0);
1082}
1083
1084NativeProcessLinux::OperationArgs::~OperationArgs()
1085{
1086 sem_destroy(&m_semaphore);
1087}
1088
1089NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001090 Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001091 char const **argv,
1092 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001093 const std::string &stdin_path,
1094 const std::string &stdout_path,
1095 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001096 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001097 const ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001098 : OperationArgs(monitor),
1099 m_module(module),
1100 m_argv(argv),
1101 m_envp(envp),
1102 m_stdin_path(stdin_path),
1103 m_stdout_path(stdout_path),
1104 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001105 m_working_dir(working_dir),
1106 m_launch_info(launch_info)
1107{
1108}
Todd Fialaaf245d12014-06-30 21:05:18 +00001109
1110NativeProcessLinux::LaunchArgs::~LaunchArgs()
1111{ }
1112
1113NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1114 lldb::pid_t pid)
1115 : OperationArgs(monitor), m_pid(pid) { }
1116
1117NativeProcessLinux::AttachArgs::~AttachArgs()
1118{ }
1119
1120// -----------------------------------------------------------------------------
1121// Public Static Methods
1122// -----------------------------------------------------------------------------
1123
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001124Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001125NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001126 Module *exe_module,
1127 ProcessLaunchInfo &launch_info,
1128 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001129 NativeProcessProtocolSP &native_process_sp)
1130{
1131 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1132
1133 Error error;
1134
1135 // Verify the working directory is valid if one was specified.
1136 const char* working_dir = launch_info.GetWorkingDirectory ();
1137 if (working_dir)
1138 {
1139 FileSpec working_dir_fs (working_dir, true);
1140 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1141 {
1142 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1143 return error;
1144 }
1145 }
1146
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001147 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001148
1149 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001150 std::string stdin_path;
1151 std::string stdout_path;
1152 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001153
1154 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001155 if (file_action)
1156 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001157
1158 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001159 if (file_action)
1160 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001161
1162 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001163 if (file_action)
1164 stderr_path = file_action->GetPath ();
1165
1166 if (log)
1167 {
1168 if (!stdin_path.empty ())
1169 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1170 else
1171 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1172
1173 if (!stdout_path.empty ())
1174 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1175 else
1176 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1177
1178 if (!stderr_path.empty ())
1179 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1180 else
1181 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1182 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001183
1184 // Create the NativeProcessLinux in launch mode.
1185 native_process_sp.reset (new NativeProcessLinux ());
1186
1187 if (log)
1188 {
1189 int i = 0;
1190 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1191 {
1192 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1193 ++i;
1194 }
1195 }
1196
1197 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1198 {
1199 native_process_sp.reset ();
1200 error.SetErrorStringWithFormat ("failed to register the native delegate");
1201 return error;
1202 }
1203
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001204 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001205 exe_module,
1206 launch_info.GetArguments ().GetConstArgumentVector (),
1207 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1208 stdin_path,
1209 stdout_path,
1210 stderr_path,
1211 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001212 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001213 error);
1214
1215 if (error.Fail ())
1216 {
1217 native_process_sp.reset ();
1218 if (log)
1219 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1220 return error;
1221 }
1222
1223 launch_info.SetProcessID (native_process_sp->GetID ());
1224
1225 return error;
1226}
1227
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001228Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001229NativeProcessLinux::AttachToProcess (
1230 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001231 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 NativeProcessProtocolSP &native_process_sp)
1233{
1234 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1235 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1236 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1237
1238 // Grab the current platform architecture. This should be Linux,
1239 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001240 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 if (!platform_sp)
1242 return Error("failed to get a valid default platform");
1243
1244 // Retrieve the architecture for the running process.
1245 ArchSpec process_arch;
1246 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1247 if (!error.Success ())
1248 return error;
1249
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001250 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001251
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001252 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001253 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001254 error.SetErrorStringWithFormat ("failed to register the native delegate");
1255 return error;
1256 }
1257
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001258 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001260 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001261
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001262 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001263 return error;
1264}
1265
1266// -----------------------------------------------------------------------------
1267// Public Instance Methods
1268// -----------------------------------------------------------------------------
1269
1270NativeProcessLinux::NativeProcessLinux () :
1271 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1272 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001273 m_operation_thread (),
1274 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001275 m_operation (nullptr),
1276 m_operation_mutex (),
1277 m_operation_pending (),
1278 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001279 m_supports_mem_region (eLazyBoolCalculate),
1280 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001281 m_mem_region_cache_mutex (),
1282 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1283 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001284{
1285}
1286
1287//------------------------------------------------------------------------------
1288/// The basic design of the NativeProcessLinux is built around two threads.
1289///
1290/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1291/// for changes in the debugee state. When a change is detected a
1292/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1293/// "drives" state changes in the debugger.
1294///
1295/// The second thread (@see OperationThread) is responsible for two things 1)
1296/// launching or attaching to the inferior process, and then 2) servicing
1297/// operations such as register reads/writes, stepping, etc. See the comments
1298/// on the Operation class for more info as to why this is needed.
1299void
1300NativeProcessLinux::LaunchInferior (
1301 Module *module,
1302 const char *argv[],
1303 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001304 const std::string &stdin_path,
1305 const std::string &stdout_path,
1306 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001307 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001308 const ProcessLaunchInfo &launch_info,
1309 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001310{
1311 if (module)
1312 m_arch = module->GetArchitecture ();
1313
Chaoren Linfa03ad22015-02-03 01:50:42 +00001314 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001315
1316 std::unique_ptr<LaunchArgs> args(
1317 new LaunchArgs(
1318 this, module, argv, envp,
1319 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001320 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001321
Chaoren Linfa03ad22015-02-03 01:50:42 +00001322 sem_init (&m_operation_pending, 0, 0);
1323 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001324
Chaoren Linfa03ad22015-02-03 01:50:42 +00001325 StartLaunchOpThread (args.get(), error);
1326 if (!error.Success ())
1327 return;
1328
1329 error = StartCoordinatorThread ();
1330 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001331 return;
1332
1333WAIT_AGAIN:
1334 // Wait for the operation thread to initialize.
1335 if (sem_wait(&args->m_semaphore))
1336 {
1337 if (errno == EINTR)
1338 goto WAIT_AGAIN;
1339 else
1340 {
1341 error.SetErrorToErrno();
1342 return;
1343 }
1344 }
1345
1346 // Check that the launch was a success.
1347 if (!args->m_error.Success())
1348 {
1349 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001350 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001351 error = args->m_error;
1352 return;
1353 }
1354
1355 // Finally, start monitoring the child process for change in state.
1356 m_monitor_thread = Host::StartMonitoringChildProcess(
1357 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001358 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001359 {
1360 error.SetErrorToGenericError();
1361 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1362 return;
1363 }
1364}
1365
1366void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001367NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001368{
1369 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1370 if (log)
1371 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1372
1373 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001374 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001375 if (!platform_sp)
1376 {
1377 if (log)
1378 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1379 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001380 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001381 }
1382
1383 // Gather info about the process.
1384 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001385 if (!platform_sp->GetProcessInfo (pid, process_info))
1386 {
1387 if (log)
1388 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1389 error.SetErrorString ("failed to get process info");
1390 return;
1391 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001392
1393 // Resolve the executable module
1394 ModuleSP exe_module_sp;
1395 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001396 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001397 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001398 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001399 if (!error.Success())
1400 return;
1401
1402 // Set the architecture to the exe architecture.
1403 m_arch = exe_module_sp->GetArchitecture();
1404 if (log)
1405 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1406
1407 m_pid = pid;
1408 SetState(eStateAttaching);
1409
1410 sem_init (&m_operation_pending, 0, 0);
1411 sem_init (&m_operation_done, 0, 0);
1412
1413 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1414
1415 StartAttachOpThread(args.get (), error);
1416 if (!error.Success ())
1417 return;
1418
Chaoren Linfa03ad22015-02-03 01:50:42 +00001419 error = StartCoordinatorThread ();
1420 if (!error.Success ())
1421 return;
1422
Todd Fialaaf245d12014-06-30 21:05:18 +00001423WAIT_AGAIN:
1424 // Wait for the operation thread to initialize.
1425 if (sem_wait (&args->m_semaphore))
1426 {
1427 if (errno == EINTR)
1428 goto WAIT_AGAIN;
1429 else
1430 {
1431 error.SetErrorToErrno ();
1432 return;
1433 }
1434 }
1435
1436 // Check that the attach was a success.
1437 if (!args->m_error.Success ())
1438 {
1439 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001440 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001441 error = args->m_error;
1442 return;
1443 }
1444
1445 // Finally, start monitoring the child process for change in state.
1446 m_monitor_thread = Host::StartMonitoringChildProcess (
1447 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001448 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001449 {
1450 error.SetErrorToGenericError ();
1451 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1452 return;
1453 }
1454}
1455
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001456void
1457NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001458{
1459 StopMonitor();
1460}
1461
1462//------------------------------------------------------------------------------
1463// Thread setup and tear down.
1464
1465void
1466NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1467{
1468 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1469
Zachary Turneracee96a2014-09-23 18:32:09 +00001470 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001471 return;
1472
Zachary Turner39de3112014-09-09 20:54:56 +00001473 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001474}
1475
1476void *
1477NativeProcessLinux::LaunchOpThread(void *arg)
1478{
1479 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1480
1481 if (!Launch(args)) {
1482 sem_post(&args->m_semaphore);
1483 return NULL;
1484 }
1485
1486 ServeOperation(args);
1487 return NULL;
1488}
1489
1490bool
1491NativeProcessLinux::Launch(LaunchArgs *args)
1492{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001493 assert (args && "null args");
1494 if (!args)
1495 return false;
1496
Todd Fialaaf245d12014-06-30 21:05:18 +00001497 NativeProcessLinux *monitor = args->m_monitor;
1498 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001499
1500 const char **argv = args->m_argv;
1501 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001502 const char *working_dir = args->m_working_dir;
1503
1504 lldb_utility::PseudoTerminal terminal;
1505 const size_t err_len = 1024;
1506 char err_str[err_len];
1507 lldb::pid_t pid;
1508 NativeThreadProtocolSP thread_sp;
1509
1510 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001511
1512 // Propagate the environment if one is not supplied.
1513 if (envp == NULL || envp[0] == NULL)
1514 envp = const_cast<const char **>(environ);
1515
1516 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1517 {
1518 args->m_error.SetErrorToGenericError();
1519 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001520 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001521 }
1522
1523 // Recognized child exit status codes.
1524 enum {
1525 ePtraceFailed = 1,
1526 eDupStdinFailed,
1527 eDupStdoutFailed,
1528 eDupStderrFailed,
1529 eChdirFailed,
1530 eExecFailed,
1531 eSetGidFailed
1532 };
1533
1534 // Child process.
1535 if (pid == 0)
1536 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001537 // FIXME consider opening a pipe between parent/child and have this forked child
1538 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001539
Todd Fiala75f47c32014-10-11 21:42:09 +00001540 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001541 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1542 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001543 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001544
Pavel Labath493c3a12015-02-04 10:36:57 +00001545 // terminal has already dupped the tty descriptors to stdin/out/err.
1546 // This closes original fd from which they were copied (and avoids
1547 // leaking descriptors to the debugged process.
1548 terminal.CloseSlaveFileDescriptor();
1549
Todd Fialaaf245d12014-06-30 21:05:18 +00001550 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001551 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001552 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001553
1554 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001555 if (setpgid(0, 0) != 0)
1556 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001557 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001558 // Don't allow this to prevent an inferior exec.
1559 }
1560
1561 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001562 if (!args->m_stdin_path.empty ())
1563 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001564 exit(eDupStdinFailed);
1565
Todd Fiala75f47c32014-10-11 21:42:09 +00001566 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001567 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001568 exit(eDupStdoutFailed);
1569
Todd Fiala75f47c32014-10-11 21:42:09 +00001570 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001571 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001572 exit(eDupStderrFailed);
1573
1574 // Change working directory
1575 if (working_dir != NULL && working_dir[0])
1576 if (0 != ::chdir(working_dir))
1577 exit(eChdirFailed);
1578
Todd Fiala0bce1b62014-08-17 00:10:50 +00001579 // Disable ASLR if requested.
1580 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1581 {
1582 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1583 if (old_personality == -1)
1584 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001585 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001586 }
1587 else
1588 {
1589 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1590 if (new_personality == -1)
1591 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001592 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001593 }
1594 else
1595 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001596 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001597 }
1598 }
1599 }
1600
Todd Fiala75f47c32014-10-11 21:42:09 +00001601 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001602 execve(argv[0],
1603 const_cast<char *const *>(argv),
1604 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001605
1606 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001607 exit(eExecFailed);
1608 }
1609
Todd Fiala75f47c32014-10-11 21:42:09 +00001610 //
1611 // This is the parent code here.
1612 //
1613 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1614
Todd Fialaaf245d12014-06-30 21:05:18 +00001615 // Wait for the child process to trap on its call to execve.
1616 ::pid_t wpid;
1617 int status;
1618 if ((wpid = waitpid(pid, &status, 0)) < 0)
1619 {
1620 args->m_error.SetErrorToErrno();
1621
1622 if (log)
1623 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1624
1625 // Mark the inferior as invalid.
1626 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1627 monitor->SetState (StateType::eStateInvalid);
1628
Todd Fiala75f47c32014-10-11 21:42:09 +00001629 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001630 }
1631 else if (WIFEXITED(status))
1632 {
1633 // open, dup or execve likely failed for some reason.
1634 args->m_error.SetErrorToGenericError();
1635 switch (WEXITSTATUS(status))
1636 {
1637 case ePtraceFailed:
1638 args->m_error.SetErrorString("Child ptrace failed.");
1639 break;
1640 case eDupStdinFailed:
1641 args->m_error.SetErrorString("Child open stdin failed.");
1642 break;
1643 case eDupStdoutFailed:
1644 args->m_error.SetErrorString("Child open stdout failed.");
1645 break;
1646 case eDupStderrFailed:
1647 args->m_error.SetErrorString("Child open stderr failed.");
1648 break;
1649 case eChdirFailed:
1650 args->m_error.SetErrorString("Child failed to set working directory.");
1651 break;
1652 case eExecFailed:
1653 args->m_error.SetErrorString("Child exec failed.");
1654 break;
1655 case eSetGidFailed:
1656 args->m_error.SetErrorString("Child setgid failed.");
1657 break;
1658 default:
1659 args->m_error.SetErrorString("Child returned unknown exit status.");
1660 break;
1661 }
1662
1663 if (log)
1664 {
1665 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1666 __FUNCTION__,
1667 WEXITSTATUS(status));
1668 }
1669
1670 // Mark the inferior as invalid.
1671 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1672 monitor->SetState (StateType::eStateInvalid);
1673
Todd Fiala75f47c32014-10-11 21:42:09 +00001674 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001675 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001676 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001677 "Could not sync with inferior process.");
1678
1679 if (log)
1680 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1681
Chaoren Lin97ccc292015-02-03 01:51:12 +00001682 args->m_error = SetDefaultPtraceOpts(pid);
1683 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001684 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001685 if (log)
1686 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1687 __FUNCTION__,
1688 args->m_error.AsCString ());
1689
1690 // Mark the inferior as invalid.
1691 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1692 monitor->SetState (StateType::eStateInvalid);
1693
Todd Fiala75f47c32014-10-11 21:42:09 +00001694 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001695 }
1696
1697 // Release the master terminal descriptor and pass it off to the
1698 // NativeProcessLinux instance. Similarly stash the inferior pid.
1699 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1700 monitor->m_pid = pid;
1701
1702 // Set the terminal fd to be in non blocking mode (it simplifies the
1703 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1704 // descriptor to read from).
1705 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1706 {
1707 if (log)
1708 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1709 __FUNCTION__,
1710 args->m_error.AsCString ());
1711
1712 // Mark the inferior as invalid.
1713 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1714 monitor->SetState (StateType::eStateInvalid);
1715
Todd Fiala75f47c32014-10-11 21:42:09 +00001716 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001717 }
1718
1719 if (log)
1720 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1721
Chaoren Linfa03ad22015-02-03 01:50:42 +00001722 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001723 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001724 monitor->NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001725 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001726
1727 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001728 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001729 monitor->SetState (StateType::eStateStopped);
1730
Todd Fialaaf245d12014-06-30 21:05:18 +00001731 if (log)
1732 {
1733 if (args->m_error.Success ())
1734 {
1735 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1736 }
1737 else
1738 {
1739 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1740 __FUNCTION__,
1741 args->m_error.AsCString ());
1742 }
1743 }
1744 return args->m_error.Success();
1745}
1746
1747void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001748NativeProcessLinux::StartAttachOpThread(AttachArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001749{
1750 static const char *g_thread_name = "lldb.process.linux.operation";
1751
Zachary Turneracee96a2014-09-23 18:32:09 +00001752 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001753 return;
1754
Zachary Turner39de3112014-09-09 20:54:56 +00001755 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001756}
1757
1758void *
1759NativeProcessLinux::AttachOpThread(void *arg)
1760{
1761 AttachArgs *args = static_cast<AttachArgs*>(arg);
1762
1763 if (!Attach(args)) {
1764 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001765 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001766 }
1767
1768 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001769 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001770}
1771
1772bool
1773NativeProcessLinux::Attach(AttachArgs *args)
1774{
1775 lldb::pid_t pid = args->m_pid;
1776
1777 NativeProcessLinux *monitor = args->m_monitor;
1778 lldb::ThreadSP inferior;
1779 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1780
1781 // Use a map to keep track of the threads which we have attached/need to attach.
1782 Host::TidMap tids_to_attach;
1783 if (pid <= 1)
1784 {
1785 args->m_error.SetErrorToGenericError();
1786 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1787 goto FINISH;
1788 }
1789
1790 while (Host::FindProcessThreads(pid, tids_to_attach))
1791 {
1792 for (Host::TidMap::iterator it = tids_to_attach.begin();
1793 it != tids_to_attach.end();)
1794 {
1795 if (it->second == false)
1796 {
1797 lldb::tid_t tid = it->first;
1798
1799 // Attach to the requested process.
1800 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001801 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1802 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001803 {
1804 // No such thread. The thread may have exited.
1805 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001806 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001807 {
1808 it = tids_to_attach.erase(it);
1809 continue;
1810 }
1811 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001812 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001813 }
1814
1815 int status;
1816 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1817 // At this point we should have a thread stopped if waitpid succeeds.
1818 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1819 {
1820 // No such thread. The thread may have exited.
1821 // More error handling may be needed.
1822 if (errno == ESRCH)
1823 {
1824 it = tids_to_attach.erase(it);
1825 continue;
1826 }
1827 else
1828 {
1829 args->m_error.SetErrorToErrno();
1830 goto FINISH;
1831 }
1832 }
1833
Chaoren Lin97ccc292015-02-03 01:51:12 +00001834 args->m_error = SetDefaultPtraceOpts(tid);
1835 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001836 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001837
1838
1839 if (log)
1840 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1841
1842 it->second = true;
1843
1844 // Create the thread, mark it as stopped.
1845 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1846 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001847
1848 // This will notify this is a new thread and tell the system it is stopped.
1849 monitor->NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001850 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001851 monitor->SetCurrentThreadID (thread_sp->GetID ());
1852 }
1853
1854 // move the loop forward
1855 ++it;
1856 }
1857 }
1858
1859 if (tids_to_attach.size() > 0)
1860 {
1861 monitor->m_pid = pid;
1862 // Let our process instance know the thread has stopped.
1863 monitor->SetState (StateType::eStateStopped);
1864 }
1865 else
1866 {
1867 args->m_error.SetErrorToGenericError();
1868 args->m_error.SetErrorString("No such process.");
1869 }
1870
1871 FINISH:
1872 return args->m_error.Success();
1873}
1874
Chaoren Lin97ccc292015-02-03 01:51:12 +00001875Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001876NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1877{
1878 long ptrace_opts = 0;
1879
1880 // Have the child raise an event on exit. This is used to keep the child in
1881 // limbo until it is destroyed.
1882 ptrace_opts |= PTRACE_O_TRACEEXIT;
1883
1884 // Have the tracer trace threads which spawn in the inferior process.
1885 // TODO: if we want to support tracing the inferiors' child, add the
1886 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1887 ptrace_opts |= PTRACE_O_TRACECLONE;
1888
1889 // Have the tracer notify us before execve returns
1890 // (needed to disable legacy SIGTRAP generation)
1891 ptrace_opts |= PTRACE_O_TRACEEXEC;
1892
Chaoren Lin97ccc292015-02-03 01:51:12 +00001893 Error error;
1894 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1895 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001896}
1897
1898static ExitType convert_pid_status_to_exit_type (int status)
1899{
1900 if (WIFEXITED (status))
1901 return ExitType::eExitTypeExit;
1902 else if (WIFSIGNALED (status))
1903 return ExitType::eExitTypeSignal;
1904 else if (WIFSTOPPED (status))
1905 return ExitType::eExitTypeStop;
1906 else
1907 {
1908 // We don't know what this is.
1909 return ExitType::eExitTypeInvalid;
1910 }
1911}
1912
1913static int convert_pid_status_to_return_code (int status)
1914{
1915 if (WIFEXITED (status))
1916 return WEXITSTATUS (status);
1917 else if (WIFSIGNALED (status))
1918 return WTERMSIG (status);
1919 else if (WIFSTOPPED (status))
1920 return WSTOPSIG (status);
1921 else
1922 {
1923 // We don't know what this is.
1924 return ExitType::eExitTypeInvalid;
1925 }
1926}
1927
1928// Main process monitoring waitpid-loop handler.
1929bool
1930NativeProcessLinux::MonitorCallback(void *callback_baton,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001931 lldb::pid_t pid,
1932 bool exited,
1933 int signal,
1934 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001935{
1936 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1937
1938 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1939 assert (process && "process is null");
1940 if (!process)
1941 {
1942 if (log)
1943 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1944 return true;
1945 }
1946
1947 // Certain activities differ based on whether the pid is the tid of the main thread.
1948 const bool is_main_thread = (pid == process->GetID ());
1949
1950 // Assume we keep monitoring by default.
1951 bool stop_monitoring = false;
1952
1953 // Handle when the thread exits.
1954 if (exited)
1955 {
1956 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001957 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 +00001958
1959 // This is a thread that exited. Ensure we're not tracking it anymore.
1960 const bool thread_found = process->StopTrackingThread (pid);
1961
Chaoren Linfa03ad22015-02-03 01:50:42 +00001962 // Make sure the thread state coordinator knows about this.
1963 process->NotifyThreadDeath (pid);
1964
Todd Fialaaf245d12014-06-30 21:05:18 +00001965 if (is_main_thread)
1966 {
1967 // We only set the exit status and notify the delegate if we haven't already set the process
1968 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1969 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001970 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001971 if (!already_notified)
1972 {
1973 if (log)
1974 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (process->GetState ()));
1975 // The main thread exited. We're done monitoring. Report to delegate.
1976 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1977
1978 // Notify delegate that our process has exited.
1979 process->SetState (StateType::eStateExited, true);
1980 }
1981 else
1982 {
1983 if (log)
1984 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1985 }
1986 return true;
1987 }
1988 else
1989 {
1990 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1991 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1992 // and we would have done an all-stop then.
1993 if (log)
1994 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1995
1996 // Not the main thread, we keep going.
1997 return false;
1998 }
1999 }
2000
2001 // Get details on the signal raised.
2002 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002003 const auto err = process->GetSignalInfo(pid, &info);
2004 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002005 {
2006 // We have retrieved the signal info. Dispatch appropriately.
2007 if (info.si_signo == SIGTRAP)
2008 process->MonitorSIGTRAP(&info, pid);
2009 else
2010 process->MonitorSignal(&info, pid, exited);
2011
2012 stop_monitoring = false;
2013 }
2014 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002015 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002016 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002017 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002018 // This is a group stop reception for this tid.
2019 if (log)
2020 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2021 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002022 }
2023 else
2024 {
2025 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2026
2027 // A return value of ESRCH means the thread/process is no longer on the system,
2028 // so it was killed somehow outside of our control. Either way, we can't do anything
2029 // with it anymore.
2030
2031 // We stop monitoring if it was the main thread.
2032 stop_monitoring = is_main_thread;
2033
2034 // Stop tracking the metadata for the thread since it's entirely off the system now.
2035 const bool thread_found = process->StopTrackingThread (pid);
2036
Chaoren Linfa03ad22015-02-03 01:50:42 +00002037 // Make sure the thread state coordinator knows about this.
2038 process->NotifyThreadDeath (pid);
2039
Todd Fialaaf245d12014-06-30 21:05:18 +00002040 if (log)
2041 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002042 __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 +00002043
2044 if (is_main_thread)
2045 {
2046 // Notify the delegate - our process is not available but appears to have been killed outside
2047 // our control. Is eStateExited the right exit state in this case?
2048 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2049 process->SetState (StateType::eStateExited, true);
2050 }
2051 else
2052 {
2053 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2054 if (log)
2055 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, process->GetID (), pid);
2056 }
2057 }
2058 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002059
2060 return stop_monitoring;
2061}
2062
2063void
2064NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2065{
2066 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2067 const bool is_main_thread = (pid == GetID ());
2068
2069 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2070 if (!info)
2071 return;
2072
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002073 Mutex::Locker locker (m_threads_mutex);
2074
Todd Fialaaf245d12014-06-30 21:05:18 +00002075 // See if we can find a thread for this signal.
2076 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2077 if (!thread_sp)
2078 {
2079 if (log)
2080 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2081 }
2082
2083 switch (info->si_code)
2084 {
2085 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2086 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2087 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2088
2089 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2090 {
2091 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2092
Chaoren Linfa03ad22015-02-03 01:50:42 +00002093 // The main thread is stopped here.
2094 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002095 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002096 NotifyThreadStop (pid);
2097
Todd Fialaaf245d12014-06-30 21:05:18 +00002098 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002099 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002100 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002101 tid = static_cast<lldb::tid_t> (event_message);
2102 if (log)
2103 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002104
Chaoren Linfa03ad22015-02-03 01:50:42 +00002105 // If we don't track the thread yet: create it, mark as stopped.
2106 // If we do track it, this is the wait we needed. Now resume the new thread.
2107 // In all cases, resume the current (i.e. main process) thread.
2108 bool created_now = false;
2109 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2110 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2111
2112 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2113 if (!created_now)
2114 {
2115 // We can now resume the newly created thread since it is fully created.
2116 NotifyThreadCreateStopped (tid);
2117 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002118 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002119 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002120 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002121 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002122 },
2123 CoordinatorErrorHandler);
2124 }
2125 else
2126 {
2127 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2128 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002129 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetLaunching ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002130 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002131 }
2132 else
2133 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002134 if (log)
2135 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 +00002136 }
2137
2138 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002139 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002140 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002141 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002142 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002143 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002144 },
2145 CoordinatorErrorHandler);
2146
Todd Fialaaf245d12014-06-30 21:05:18 +00002147 break;
2148 }
2149
2150 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002151 {
2152 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002153 if (log)
2154 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002155
Chaoren Linfa03ad22015-02-03 01:50:42 +00002156 // The thread state coordinator needs to reset due to the exec.
2157 m_coordinator_up->ResetForExec ();
2158
2159 // 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 +00002160 if (log)
2161 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2162
2163 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002164 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002165 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2166 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002167 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002168 main_thread_sp = thread_sp;
2169 if (log)
2170 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002171 }
2172 else
2173 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002174 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002175 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002176 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002177 }
2178 }
2179
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002180 m_threads.clear ();
2181
2182 if (main_thread_sp)
2183 {
2184 m_threads.push_back (main_thread_sp);
2185 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002186 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002187 }
2188 else
2189 {
2190 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2191 if (log)
2192 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2193 }
2194
Chaoren Linfa03ad22015-02-03 01:50:42 +00002195 // Tell coordinator about about the "new" (since exec) stopped main thread.
2196 const lldb::tid_t main_thread_tid = GetID ();
2197 NotifyThreadCreateStopped (main_thread_tid);
2198
2199 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2200 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002201 // Let our delegate know we have just exec'd.
2202 NotifyDidExec ();
2203
2204 // If we have a main thread, indicate we are stopped.
2205 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002206
2207 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002208 CallAfterRunningThreadsStop (pid,
2209 [=] (lldb::tid_t signaling_tid)
2210 {
2211 SetState (StateType::eStateStopped, true);
2212 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002213
Todd Fialaaf245d12014-06-30 21:05:18 +00002214 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002215 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002216
2217 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2218 {
2219 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002220
2221 // This thread is currently stopped. It's not actually dead yet, just about to be.
2222 NotifyThreadStop (pid);
2223
Todd Fialaaf245d12014-06-30 21:05:18 +00002224 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002225 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002226 data = -1;
2227
2228 if (log)
2229 {
2230 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2231 __FUNCTION__,
2232 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2233 pid,
2234 is_main_thread ? "is main thread" : "not main thread");
2235 }
2236
Todd Fialaaf245d12014-06-30 21:05:18 +00002237 if (is_main_thread)
2238 {
2239 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002240 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002241
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002242 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002243 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002244 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002245 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002246 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002247 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002248 },
2249 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002250
2251 break;
2252 }
2253
2254 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002255 case TRAP_TRACE: // We receive this on single stepping.
2256 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002257 if (thread_sp)
2258 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002259 // If a watchpoint was hit, report it
2260 uint32_t wp_index;
2261 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2262 if (error.Fail() && log)
2263 log->Printf("NativeProcessLinux::%s() "
2264 "received error while checking for watchpoint hits, "
2265 "pid = %" PRIu64 " error = %s",
2266 __FUNCTION__, pid, error.AsCString());
2267 if (wp_index != LLDB_INVALID_INDEX32)
2268 {
2269 MonitorWatchpoint(pid, thread_sp, wp_index);
2270 break;
2271 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002272 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002273 // Otherwise, report step over
2274 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002275 break;
2276
2277 case SI_KERNEL:
2278 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002279 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002280 break;
2281
2282 case SIGTRAP:
2283 case (SIGTRAP | 0x80):
2284 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002285 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2286
2287 // This thread is currently stopped.
2288 NotifyThreadStop (pid);
2289 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002290 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002291
2292
Todd Fialaaf245d12014-06-30 21:05:18 +00002293 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002294 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002295 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002296 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002297 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002298 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002299 },
2300 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002301 break;
2302
2303 default:
2304 assert(false && "Unexpected SIGTRAP code!");
2305 if (log)
2306 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)));
2307 break;
2308
2309 }
2310}
2311
2312void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002313NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2314{
2315 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2316 if (log)
2317 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2318 __FUNCTION__, pid);
2319
2320 if (thread_sp)
2321 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2322
2323 // This thread is currently stopped.
2324 NotifyThreadStop(pid);
2325
2326 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2327 // This would have already happened at the time the Resume() with step operation was signaled.
2328 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2329 // once all running threads have checked in as stopped.
2330 SetCurrentThreadID(pid);
2331 // Tell the process we have a stop (from software breakpoint).
2332 CallAfterRunningThreadsStop(pid,
2333 [=](lldb::tid_t signaling_tid)
2334 {
2335 SetState(StateType::eStateStopped, true);
2336 });
2337}
2338
2339void
2340NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2341{
2342 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2343 if (log)
2344 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2345 __FUNCTION__, pid);
2346
2347 // This thread is currently stopped.
2348 NotifyThreadStop(pid);
2349
2350 // Mark the thread as stopped at breakpoint.
2351 if (thread_sp)
2352 {
2353 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2354 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2355 if (error.Fail())
2356 if (log)
2357 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2358 __FUNCTION__, pid, error.AsCString());
2359 }
2360 else
2361 if (log)
2362 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2363 "warning, cannot process software breakpoint since no thread metadata",
2364 __FUNCTION__, pid);
2365
2366
2367 // We need to tell all other running threads before we notify the delegate about this stop.
2368 CallAfterRunningThreadsStop(pid,
2369 [=](lldb::tid_t deferred_notification_tid)
2370 {
2371 SetCurrentThreadID(deferred_notification_tid);
2372 // Tell the process we have a stop (from software breakpoint).
2373 SetState(StateType::eStateStopped, true);
2374 });
2375}
2376
2377void
2378NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2379{
2380 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2381 if (log)
2382 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2383 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2384 __FUNCTION__, pid, wp_index);
2385
2386 // This thread is currently stopped.
2387 NotifyThreadStop(pid);
2388
2389 // Mark the thread as stopped at watchpoint.
2390 // The address is at (lldb::addr_t)info->si_addr if we need it.
2391 lldbassert(thread_sp && "thread_sp cannot be NULL");
2392 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2393
2394 // We need to tell all other running threads before we notify the delegate about this stop.
2395 CallAfterRunningThreadsStop(pid,
2396 [=](lldb::tid_t deferred_notification_tid)
2397 {
2398 SetCurrentThreadID(deferred_notification_tid);
2399 // Tell the process we have a stop (from watchpoint).
2400 SetState(StateType::eStateStopped, true);
2401 });
2402}
2403
2404void
Todd Fialaaf245d12014-06-30 21:05:18 +00002405NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2406{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002407 assert (info && "null info");
2408 if (!info)
2409 return;
2410
2411 const int signo = info->si_signo;
2412 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002413
2414 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2415
2416 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2417 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2418 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2419 //
2420 // IOW, user generated signals never generate what we consider to be a
2421 // "crash".
2422 //
2423 // Similarly, ACK signals generated by this monitor.
2424
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002425 Mutex::Locker locker (m_threads_mutex);
2426
Todd Fialaaf245d12014-06-30 21:05:18 +00002427 // See if we can find a thread for this signal.
2428 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2429 if (!thread_sp)
2430 {
2431 if (log)
2432 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2433 }
2434
2435 // Handle the signal.
2436 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2437 {
2438 if (log)
2439 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2440 __FUNCTION__,
2441 GetUnixSignals ().GetSignalAsCString (signo),
2442 signo,
2443 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2444 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002445 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002446 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002447 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002448
Todd Fiala58a2f662014-08-12 17:02:07 +00002449 // Check for new thread notification.
2450 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2451 {
2452 // A new thread creation is being signaled. This is one of two parts that come in
2453 // a non-deterministic order. pid is the thread id.
2454 if (log)
2455 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2456 __FUNCTION__, GetID (), pid);
2457
2458 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002459 bool created_now = false;
2460 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002461 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2462
2463 // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002464 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002465 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002466 // We can now resume the newly created thread since it is fully created.
2467 NotifyThreadCreateStopped (pid);
2468 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002469 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002470 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002471 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002472 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002473 },
2474 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002475 }
2476 else
2477 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002478 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2479 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002480 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002481 }
2482
Todd Fiala58a2f662014-08-12 17:02:07 +00002483 // Done handling.
2484 return;
2485 }
2486
2487 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002488 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002489 {
2490 // This is a tgkill()-based stop.
2491 if (thread_sp)
2492 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002493 if (log)
2494 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2495 __FUNCTION__,
2496 GetID (),
2497 pid);
2498
Chaoren Linaab58632015-02-03 01:50:57 +00002499 // Check that we're not already marked with a stop reason.
2500 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2501 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2502 // and that, without an intervening resume, we received another stop. It is more likely
2503 // that we are missing the marking of a run state somewhere if we find that the thread was
2504 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002505 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2506 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002507
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002508 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002509 if (!StateIsStoppedState (thread_state, false))
2510 {
2511 // An inferior thread just stopped, but was not the primary cause of the process stop.
2512 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2513 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002514 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002515 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002516 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002517 }
2518 else
2519 {
2520 if (log)
2521 {
2522 // Retrieve the signal name if the thread was stopped by a signal.
2523 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002524 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002525 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2526 if (!signal_name)
2527 signal_name = "<no-signal-name>";
2528
2529 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",
2530 __FUNCTION__,
2531 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002532 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002533 StateAsCString (thread_state),
2534 stop_signo,
2535 signal_name);
2536 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002537 // Tell the thread state coordinator about the stop.
2538 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002539 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002540 }
2541
2542 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002543 return;
2544 }
2545
2546 if (log)
2547 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2548
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002549 // This thread is stopped.
2550 NotifyThreadStop (pid);
2551
Todd Fialaaf245d12014-06-30 21:05:18 +00002552 switch (signo)
2553 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002554 case SIGSTOP:
2555 {
2556 if (log)
2557 {
2558 if (is_from_llgs)
2559 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2560 else
2561 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2562 }
2563
Chaoren Linfa03ad22015-02-03 01:50:42 +00002564 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2565 // This thread will get stopped again as part of the group-stop completion.
2566 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002567 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002568 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002569 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002570 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002571 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002572 },
2573 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002574 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002575 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002576 case SIGSEGV:
2577 case SIGILL:
2578 case SIGFPE:
2579 case SIGBUS:
2580 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002581 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002582 break;
2583 default:
2584 // This is just a pre-signal-delivery notification of the incoming signal.
2585 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002586 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002587
2588 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002589 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002590
2591 // Send a stop to the debugger after we get all other threads to stop.
2592 CallAfterRunningThreadsStop (pid,
2593 [=] (lldb::tid_t signaling_tid)
2594 {
2595 SetCurrentThreadID (signaling_tid);
2596 SetState (StateType::eStateStopped, true);
2597 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002598}
2599
2600Error
2601NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2602{
Todd Fialaaf245d12014-06-30 21:05:18 +00002603 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2604 if (log)
2605 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2606
Chaoren Lin03f12d62015-02-03 01:50:49 +00002607 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2608 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002609 int deferred_signo = 0;
2610 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002611 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002612
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002613 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002614
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002615 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002616 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002617 assert (thread_sp && "thread list should not contain NULL threads");
2618
2619 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2620
2621 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002622 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002623 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002624 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2625 __FUNCTION__, GetID (), thread_sp->GetID ());
2626 continue;
2627 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002628
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002629 if (log)
2630 {
2631 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2632 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2633 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002634
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002635 switch (action->state)
2636 {
2637 case eStateRunning:
2638 {
2639 // Run the thread, possibly feeding it the signal.
2640 const int signo = action->signal;
2641 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2642 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2643 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002644 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002645 // Pass this signal number on to the inferior to handle.
2646 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2647 if (resume_result.Success())
2648 SetState(eStateRunning, true);
2649 return resume_result;
2650 },
2651 CoordinatorErrorHandler);
2652 break;
2653 }
2654
2655 case eStateStepping:
2656 {
2657 // Request the step.
2658 const int signo = action->signal;
2659 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2660 [=](lldb::tid_t tid_to_step, bool supress_signal)
2661 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002662 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002663 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2664 assert (step_result.Success() && "SingleStep() failed");
2665 if (step_result.Success())
2666 SetState(eStateStepping, true);
2667 return step_result;
2668 },
2669 CoordinatorErrorHandler);
2670 stepping = true;
2671 break;
2672 }
2673
2674 case eStateSuspended:
2675 case eStateStopped:
2676 // if we haven't chosen a deferred signal tid yet, use this one.
2677 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002678 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002679 deferred_signal_tid = thread_sp->GetID ();
2680 deferred_signal_thread_sp = thread_sp;
2681 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002682 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002683 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002684
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002685 default:
2686 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2687 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002688 }
2689 }
2690
Chaoren Linfa03ad22015-02-03 01:50:42 +00002691 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2692 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002693 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2694 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002695 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002696 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2697 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002698 [=](lldb::tid_t deferred_notification_tid)
2699 {
Chaoren Linae29d392015-02-03 01:50:46 +00002700 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002701 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002702
2703 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002704 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00002705
2706 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002707 SetState (StateType::eStateStopped, true);
2708 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002709 }
2710
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002711 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002712}
2713
2714Error
2715NativeProcessLinux::Halt ()
2716{
2717 Error error;
2718
Todd Fialaaf245d12014-06-30 21:05:18 +00002719 if (kill (GetID (), SIGSTOP) != 0)
2720 error.SetErrorToErrno ();
2721
2722 return error;
2723}
2724
2725Error
2726NativeProcessLinux::Detach ()
2727{
2728 Error error;
2729
2730 // Tell ptrace to detach from the process.
2731 if (GetID () != LLDB_INVALID_PROCESS_ID)
2732 error = Detach (GetID ());
2733
2734 // Stop monitoring the inferior.
2735 StopMonitor ();
2736
2737 // No error.
2738 return error;
2739}
2740
2741Error
2742NativeProcessLinux::Signal (int signo)
2743{
2744 Error error;
2745
2746 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2747 if (log)
2748 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2749 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2750
2751 if (kill(GetID(), signo))
2752 error.SetErrorToErrno();
2753
2754 return error;
2755}
2756
2757Error
Chaoren Line9547b82015-02-03 01:51:00 +00002758NativeProcessLinux::Interrupt ()
2759{
2760 // Pick a running thread (or if none, a not-dead stopped thread) as
2761 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002762 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2763
2764 NativeThreadProtocolSP running_thread_sp;
2765 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002766
2767 if (log)
2768 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2769
2770 Mutex::Locker locker (m_threads_mutex);
2771
2772 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002773 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002774 // The thread shouldn't be null but lets just cover that here.
2775 if (!thread_sp)
2776 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002777
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002778 // If we have a running or stepping thread, we'll call that the
2779 // target of the interrupt.
2780 const auto thread_state = thread_sp->GetState ();
2781 if (thread_state == eStateRunning ||
2782 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002783 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002784 running_thread_sp = thread_sp;
2785 break;
2786 }
2787 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2788 {
2789 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2790 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002791 }
2792 }
2793
2794 if (!running_thread_sp && !stopped_thread_sp)
2795 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002796 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002797 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002798 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002799
Chaoren Line9547b82015-02-03 01:51:00 +00002800 return error;
2801 }
2802
2803 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2804
2805 if (log)
2806 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2807 __FUNCTION__,
2808 GetID (),
2809 running_thread_sp ? "running" : "stopped",
2810 deferred_signal_thread_sp->GetID ());
2811
2812 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2813 [=](lldb::tid_t deferred_notification_tid)
2814 {
2815 // Set the signal thread to the current thread.
2816 SetCurrentThreadID (deferred_notification_tid);
2817
2818 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002819 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00002820
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002821 // Tell the process delegate that the process is in a stopped state.
2822 SetState (StateType::eStateStopped, true);
2823 });
2824 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002825}
2826
2827Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002828NativeProcessLinux::Kill ()
2829{
2830 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2831 if (log)
2832 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2833
2834 Error error;
2835
2836 switch (m_state)
2837 {
2838 case StateType::eStateInvalid:
2839 case StateType::eStateExited:
2840 case StateType::eStateCrashed:
2841 case StateType::eStateDetached:
2842 case StateType::eStateUnloaded:
2843 // Nothing to do - the process is already dead.
2844 if (log)
2845 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2846 return error;
2847
2848 case StateType::eStateConnected:
2849 case StateType::eStateAttaching:
2850 case StateType::eStateLaunching:
2851 case StateType::eStateStopped:
2852 case StateType::eStateRunning:
2853 case StateType::eStateStepping:
2854 case StateType::eStateSuspended:
2855 // We can try to kill a process in these states.
2856 break;
2857 }
2858
2859 if (kill (GetID (), SIGKILL) != 0)
2860 {
2861 error.SetErrorToErrno ();
2862 return error;
2863 }
2864
2865 return error;
2866}
2867
2868static Error
2869ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2870{
2871 memory_region_info.Clear();
2872
2873 StringExtractor line_extractor (maps_line.c_str ());
2874
2875 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2876 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2877
2878 // Parse out the starting address
2879 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2880
2881 // Parse out hyphen separating start and end address from range.
2882 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2883 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2884
2885 // Parse out the ending address
2886 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2887
2888 // Parse out the space after the address.
2889 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2890 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2891
2892 // Save the range.
2893 memory_region_info.GetRange ().SetRangeBase (start_address);
2894 memory_region_info.GetRange ().SetRangeEnd (end_address);
2895
2896 // Parse out each permission entry.
2897 if (line_extractor.GetBytesLeft () < 4)
2898 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2899
2900 // Handle read permission.
2901 const char read_perm_char = line_extractor.GetChar ();
2902 if (read_perm_char == 'r')
2903 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2904 else
2905 {
2906 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2907 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2908 }
2909
2910 // Handle write permission.
2911 const char write_perm_char = line_extractor.GetChar ();
2912 if (write_perm_char == 'w')
2913 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2914 else
2915 {
2916 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2917 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2918 }
2919
2920 // Handle execute permission.
2921 const char exec_perm_char = line_extractor.GetChar ();
2922 if (exec_perm_char == 'x')
2923 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2924 else
2925 {
2926 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2927 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2928 }
2929
2930 return Error ();
2931}
2932
2933Error
2934NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2935{
2936 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2937 // with no perms if it is not mapped.
2938
2939 // Use an approach that reads memory regions from /proc/{pid}/maps.
2940 // Assume proc maps entries are in ascending order.
2941 // FIXME assert if we find differently.
2942 Mutex::Locker locker (m_mem_region_cache_mutex);
2943
2944 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2945 Error error;
2946
2947 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2948 {
2949 // We're done.
2950 error.SetErrorString ("unsupported");
2951 return error;
2952 }
2953
2954 // If our cache is empty, pull the latest. There should always be at least one memory region
2955 // if memory region handling is supported.
2956 if (m_mem_region_cache.empty ())
2957 {
2958 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2959 [&] (const std::string &line) -> bool
2960 {
2961 MemoryRegionInfo info;
2962 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2963 if (parse_error.Success ())
2964 {
2965 m_mem_region_cache.push_back (info);
2966 return true;
2967 }
2968 else
2969 {
2970 if (log)
2971 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2972 return false;
2973 }
2974 });
2975
2976 // If we had an error, we'll mark unsupported.
2977 if (error.Fail ())
2978 {
2979 m_supports_mem_region = LazyBool::eLazyBoolNo;
2980 return error;
2981 }
2982 else if (m_mem_region_cache.empty ())
2983 {
2984 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2985 // is supported. Assume we don't support map entries via procfs.
2986 if (log)
2987 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2988 m_supports_mem_region = LazyBool::eLazyBoolNo;
2989 error.SetErrorString ("not supported");
2990 return error;
2991 }
2992
2993 if (log)
2994 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2995
2996 // We support memory retrieval, remember that.
2997 m_supports_mem_region = LazyBool::eLazyBoolYes;
2998 }
2999 else
3000 {
3001 if (log)
3002 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3003 }
3004
3005 lldb::addr_t prev_base_address = 0;
3006
3007 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3008 // There can be a ton of regions on pthreads apps with lots of threads.
3009 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3010 {
3011 MemoryRegionInfo &proc_entry_info = *it;
3012
3013 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3014 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3015 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3016
3017 // If the target address comes before this entry, indicate distance to next region.
3018 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3019 {
3020 range_info.GetRange ().SetRangeBase (load_addr);
3021 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3022 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3023 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3024 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3025
3026 return error;
3027 }
3028 else if (proc_entry_info.GetRange ().Contains (load_addr))
3029 {
3030 // The target address is within the memory region we're processing here.
3031 range_info = proc_entry_info;
3032 return error;
3033 }
3034
3035 // The target memory address comes somewhere after the region we just parsed.
3036 }
3037
3038 // If we made it here, we didn't find an entry that contained the given address.
3039 error.SetErrorString ("address comes after final region");
3040
3041 if (log)
3042 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3043
3044 return error;
3045}
3046
3047void
3048NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3049{
3050 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3051 if (log)
3052 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3053
3054 {
3055 Mutex::Locker locker (m_mem_region_cache_mutex);
3056 if (log)
3057 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3058 m_mem_region_cache.clear ();
3059 }
3060}
3061
3062Error
3063NativeProcessLinux::AllocateMemory (
3064 lldb::addr_t size,
3065 uint32_t permissions,
3066 lldb::addr_t &addr)
3067{
3068 // FIXME implementing this requires the equivalent of
3069 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3070 // functional ThreadPlans working with Native*Protocol.
3071#if 1
3072 return Error ("not implemented yet");
3073#else
3074 addr = LLDB_INVALID_ADDRESS;
3075
3076 unsigned prot = 0;
3077 if (permissions & lldb::ePermissionsReadable)
3078 prot |= eMmapProtRead;
3079 if (permissions & lldb::ePermissionsWritable)
3080 prot |= eMmapProtWrite;
3081 if (permissions & lldb::ePermissionsExecutable)
3082 prot |= eMmapProtExec;
3083
3084 // TODO implement this directly in NativeProcessLinux
3085 // (and lift to NativeProcessPOSIX if/when that class is
3086 // refactored out).
3087 if (InferiorCallMmap(this, addr, 0, size, prot,
3088 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3089 m_addr_to_mmap_size[addr] = size;
3090 return Error ();
3091 } else {
3092 addr = LLDB_INVALID_ADDRESS;
3093 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3094 }
3095#endif
3096}
3097
3098Error
3099NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3100{
3101 // FIXME see comments in AllocateMemory - required lower-level
3102 // bits not in place yet (ThreadPlans)
3103 return Error ("not implemented");
3104}
3105
3106lldb::addr_t
3107NativeProcessLinux::GetSharedLibraryInfoAddress ()
3108{
3109#if 1
3110 // punt on this for now
3111 return LLDB_INVALID_ADDRESS;
3112#else
3113 // Return the image info address for the exe module
3114#if 1
3115 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3116
3117 ModuleSP module_sp;
3118 Error error = GetExeModuleSP (module_sp);
3119 if (error.Fail ())
3120 {
3121 if (log)
3122 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3123 return LLDB_INVALID_ADDRESS;
3124 }
3125
3126 if (module_sp == nullptr)
3127 {
3128 if (log)
3129 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3130 return LLDB_INVALID_ADDRESS;
3131 }
3132
3133 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3134 if (object_file_sp == nullptr)
3135 {
3136 if (log)
3137 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3138 return LLDB_INVALID_ADDRESS;
3139 }
3140
3141 return obj_file_sp->GetImageInfoAddress();
3142#else
3143 Target *target = &GetTarget();
3144 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3145 Address addr = obj_file->GetImageInfoAddress(target);
3146
3147 if (addr.IsValid())
3148 return addr.GetLoadAddress(target);
3149 return LLDB_INVALID_ADDRESS;
3150#endif
3151#endif // punt on this for now
3152}
3153
3154size_t
3155NativeProcessLinux::UpdateThreads ()
3156{
3157 // The NativeProcessLinux monitoring threads are always up to date
3158 // with respect to thread state and they keep the thread list
3159 // populated properly. All this method needs to do is return the
3160 // thread count.
3161 Mutex::Locker locker (m_threads_mutex);
3162 return m_threads.size ();
3163}
3164
3165bool
3166NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3167{
3168 arch = m_arch;
3169 return true;
3170}
3171
3172Error
3173NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3174{
3175 // FIXME put this behind a breakpoint protocol class that can be
3176 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003177 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003178 static const uint8_t g_i386_opcode [] = { 0xCC };
3179
3180 switch (m_arch.GetMachine ())
3181 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003182 case llvm::Triple::aarch64:
3183 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3184 return Error ();
3185
Todd Fialaaf245d12014-06-30 21:05:18 +00003186 case llvm::Triple::x86:
3187 case llvm::Triple::x86_64:
3188 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3189 return Error ();
3190
3191 default:
3192 assert(false && "CPU type not supported!");
3193 return Error ("CPU type not supported");
3194 }
3195}
3196
3197Error
3198NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3199{
3200 if (hardware)
3201 return Error ("NativeProcessLinux does not support hardware breakpoints");
3202 else
3203 return SetSoftwareBreakpoint (addr, size);
3204}
3205
3206Error
3207NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3208{
3209 // FIXME put this behind a breakpoint protocol class that can be
3210 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003211 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003212 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003213 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003214
3215 switch (m_arch.GetMachine ())
3216 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003217 case llvm::Triple::aarch64:
3218 trap_opcode_bytes = g_aarch64_opcode;
3219 actual_opcode_size = sizeof(g_aarch64_opcode);
3220 return Error ();
3221
Todd Fialaaf245d12014-06-30 21:05:18 +00003222 case llvm::Triple::x86:
3223 case llvm::Triple::x86_64:
3224 trap_opcode_bytes = g_i386_opcode;
3225 actual_opcode_size = sizeof(g_i386_opcode);
3226 return Error ();
3227
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003228 case llvm::Triple::mips64:
3229 case llvm::Triple::mips64el:
3230 trap_opcode_bytes = g_mips64_opcode;
3231 actual_opcode_size = sizeof(g_mips64_opcode);
3232 return Error ();
3233
Todd Fialaaf245d12014-06-30 21:05:18 +00003234 default:
3235 assert(false && "CPU type not supported!");
3236 return Error ("CPU type not supported");
3237 }
3238}
3239
3240#if 0
3241ProcessMessage::CrashReason
3242NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3243{
3244 ProcessMessage::CrashReason reason;
3245 assert(info->si_signo == SIGSEGV);
3246
3247 reason = ProcessMessage::eInvalidCrashReason;
3248
3249 switch (info->si_code)
3250 {
3251 default:
3252 assert(false && "unexpected si_code for SIGSEGV");
3253 break;
3254 case SI_KERNEL:
3255 // Linux will occasionally send spurious SI_KERNEL codes.
3256 // (this is poorly documented in sigaction)
3257 // One way to get this is via unaligned SIMD loads.
3258 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3259 break;
3260 case SEGV_MAPERR:
3261 reason = ProcessMessage::eInvalidAddress;
3262 break;
3263 case SEGV_ACCERR:
3264 reason = ProcessMessage::ePrivilegedAddress;
3265 break;
3266 }
3267
3268 return reason;
3269}
3270#endif
3271
3272
3273#if 0
3274ProcessMessage::CrashReason
3275NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3276{
3277 ProcessMessage::CrashReason reason;
3278 assert(info->si_signo == SIGILL);
3279
3280 reason = ProcessMessage::eInvalidCrashReason;
3281
3282 switch (info->si_code)
3283 {
3284 default:
3285 assert(false && "unexpected si_code for SIGILL");
3286 break;
3287 case ILL_ILLOPC:
3288 reason = ProcessMessage::eIllegalOpcode;
3289 break;
3290 case ILL_ILLOPN:
3291 reason = ProcessMessage::eIllegalOperand;
3292 break;
3293 case ILL_ILLADR:
3294 reason = ProcessMessage::eIllegalAddressingMode;
3295 break;
3296 case ILL_ILLTRP:
3297 reason = ProcessMessage::eIllegalTrap;
3298 break;
3299 case ILL_PRVOPC:
3300 reason = ProcessMessage::ePrivilegedOpcode;
3301 break;
3302 case ILL_PRVREG:
3303 reason = ProcessMessage::ePrivilegedRegister;
3304 break;
3305 case ILL_COPROC:
3306 reason = ProcessMessage::eCoprocessorError;
3307 break;
3308 case ILL_BADSTK:
3309 reason = ProcessMessage::eInternalStackError;
3310 break;
3311 }
3312
3313 return reason;
3314}
3315#endif
3316
3317#if 0
3318ProcessMessage::CrashReason
3319NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3320{
3321 ProcessMessage::CrashReason reason;
3322 assert(info->si_signo == SIGFPE);
3323
3324 reason = ProcessMessage::eInvalidCrashReason;
3325
3326 switch (info->si_code)
3327 {
3328 default:
3329 assert(false && "unexpected si_code for SIGFPE");
3330 break;
3331 case FPE_INTDIV:
3332 reason = ProcessMessage::eIntegerDivideByZero;
3333 break;
3334 case FPE_INTOVF:
3335 reason = ProcessMessage::eIntegerOverflow;
3336 break;
3337 case FPE_FLTDIV:
3338 reason = ProcessMessage::eFloatDivideByZero;
3339 break;
3340 case FPE_FLTOVF:
3341 reason = ProcessMessage::eFloatOverflow;
3342 break;
3343 case FPE_FLTUND:
3344 reason = ProcessMessage::eFloatUnderflow;
3345 break;
3346 case FPE_FLTRES:
3347 reason = ProcessMessage::eFloatInexactResult;
3348 break;
3349 case FPE_FLTINV:
3350 reason = ProcessMessage::eFloatInvalidOperation;
3351 break;
3352 case FPE_FLTSUB:
3353 reason = ProcessMessage::eFloatSubscriptRange;
3354 break;
3355 }
3356
3357 return reason;
3358}
3359#endif
3360
3361#if 0
3362ProcessMessage::CrashReason
3363NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3364{
3365 ProcessMessage::CrashReason reason;
3366 assert(info->si_signo == SIGBUS);
3367
3368 reason = ProcessMessage::eInvalidCrashReason;
3369
3370 switch (info->si_code)
3371 {
3372 default:
3373 assert(false && "unexpected si_code for SIGBUS");
3374 break;
3375 case BUS_ADRALN:
3376 reason = ProcessMessage::eIllegalAlignment;
3377 break;
3378 case BUS_ADRERR:
3379 reason = ProcessMessage::eIllegalAddress;
3380 break;
3381 case BUS_OBJERR:
3382 reason = ProcessMessage::eHardwareError;
3383 break;
3384 }
3385
3386 return reason;
3387}
3388#endif
3389
3390void
3391NativeProcessLinux::ServeOperation(OperationArgs *args)
3392{
3393 NativeProcessLinux *monitor = args->m_monitor;
3394
3395 // We are finised with the arguments and are ready to go. Sync with the
3396 // parent thread and start serving operations on the inferior.
3397 sem_post(&args->m_semaphore);
3398
3399 for(;;)
3400 {
3401 // wait for next pending operation
3402 if (sem_wait(&monitor->m_operation_pending))
3403 {
3404 if (errno == EINTR)
3405 continue;
3406 assert(false && "Unexpected errno from sem_wait");
3407 }
3408
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003409 // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3410 // android. We don't have to send a post to the m_operation_done semaphore because in this
3411 // case the synchronization is achieved by a Join() call
3412 if (monitor->m_operation == EXIT_OPERATION)
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003413 break;
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003414
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003415 static_cast<Operation*>(monitor->m_operation)->Execute(monitor);
Todd Fialaaf245d12014-06-30 21:05:18 +00003416
3417 // notify calling thread that operation is complete
3418 sem_post(&monitor->m_operation_done);
3419 }
3420}
3421
3422void
3423NativeProcessLinux::DoOperation(void *op)
3424{
3425 Mutex::Locker lock(m_operation_mutex);
3426
3427 m_operation = op;
3428
3429 // notify operation thread that an operation is ready to be processed
3430 sem_post(&m_operation_pending);
3431
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003432 // Don't wait for the operation to complete in case of an exit operation. The operation thread
3433 // will exit without posting to the semaphore
3434 if (m_operation == EXIT_OPERATION)
3435 return;
3436
Todd Fialaaf245d12014-06-30 21:05:18 +00003437 // wait for operation to complete
3438 while (sem_wait(&m_operation_done))
3439 {
3440 if (errno == EINTR)
3441 continue;
3442 assert(false && "Unexpected errno from sem_wait");
3443 }
3444}
3445
3446Error
3447NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3448{
3449 ReadOperation op(addr, buf, size, bytes_read);
3450 DoOperation(&op);
3451 return op.GetError ();
3452}
3453
3454Error
3455NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3456{
3457 WriteOperation op(addr, buf, size, bytes_written);
3458 DoOperation(&op);
3459 return op.GetError ();
3460}
3461
Chaoren Lin97ccc292015-02-03 01:51:12 +00003462Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003463NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003464 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003465{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003466 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003467 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003468 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003469}
3470
Chaoren Lin97ccc292015-02-03 01:51:12 +00003471Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003472NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3473 const char* reg_name, const RegisterValue &value)
3474{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003475 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003476 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003477 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003478}
3479
Chaoren Lin97ccc292015-02-03 01:51:12 +00003480Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003481NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3482{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003483 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003484 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003485 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003486}
3487
Chaoren Lin97ccc292015-02-03 01:51:12 +00003488Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003489NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3490{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003491 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003492 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003493 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003494}
3495
Chaoren Lin97ccc292015-02-03 01:51:12 +00003496Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003497NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3498{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003499 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003500 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003501 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003502}
3503
Chaoren Lin97ccc292015-02-03 01:51:12 +00003504Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003505NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3506{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003507 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003508 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003509 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003510}
3511
Chaoren Lin97ccc292015-02-03 01:51:12 +00003512Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003513NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3514{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003515 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003516 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003517 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003518}
3519
Chaoren Lin97ccc292015-02-03 01:51:12 +00003520Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003521NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3522{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003523 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003524 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003525 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003526}
3527
Chaoren Lin97ccc292015-02-03 01:51:12 +00003528Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003529NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3530{
Todd Fialaaf245d12014-06-30 21:05:18 +00003531 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3532
3533 if (log)
3534 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3535 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003536 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003537 DoOperation (&op);
3538 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003539 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3540 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003541}
3542
Chaoren Lin97ccc292015-02-03 01:51:12 +00003543Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003544NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3545{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003546 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003547 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003548 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003549}
3550
Chaoren Lin97ccc292015-02-03 01:51:12 +00003551Error
3552NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003553{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003554 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003555 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003556 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003557}
3558
Chaoren Lin97ccc292015-02-03 01:51:12 +00003559Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003560NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3561{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003562 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003563 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003564 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003565}
3566
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003567Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003568NativeProcessLinux::Detach(lldb::tid_t tid)
3569{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003570 if (tid == LLDB_INVALID_THREAD_ID)
3571 return Error();
3572
3573 DetachOperation op(tid);
3574 DoOperation(&op);
3575 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003576}
3577
3578bool
3579NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3580{
3581 int target_fd = open(path, flags, 0666);
3582
3583 if (target_fd == -1)
3584 return false;
3585
Pavel Labath493c3a12015-02-04 10:36:57 +00003586 if (dup2(target_fd, fd) == -1)
3587 return false;
3588
3589 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003590}
3591
3592void
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003593NativeProcessLinux::StopMonitorThread()
Todd Fialaaf245d12014-06-30 21:05:18 +00003594{
Zachary Turneracee96a2014-09-23 18:32:09 +00003595 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003596 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003597 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00003598 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003599 }
3600}
3601
3602void
3603NativeProcessLinux::StopMonitor()
3604{
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003605 StopMonitorThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003606 StopCoordinatorThread ();
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003607 StopOpThread();
Todd Fialaaf245d12014-06-30 21:05:18 +00003608 sem_destroy(&m_operation_pending);
3609 sem_destroy(&m_operation_done);
3610
3611 // TODO: validate whether this still holds, fix up comment.
3612 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3613 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3614 // the descriptor to a ConnectionFileDescriptor object. Consequently
3615 // even though still has the file descriptor, we shouldn't close it here.
3616}
3617
3618void
3619NativeProcessLinux::StopOpThread()
3620{
Zachary Turneracee96a2014-09-23 18:32:09 +00003621 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003622 return;
3623
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003624 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00003625 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003626}
3627
Chaoren Linfa03ad22015-02-03 01:50:42 +00003628Error
3629NativeProcessLinux::StartCoordinatorThread ()
3630{
3631 Error error;
3632 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3633 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3634
3635 // Skip if thread is already running
3636 if (m_coordinator_thread.IsJoinable())
3637 {
3638 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3639 if (log)
3640 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3641 return error;
3642 }
3643
3644 // Enable verbose logging if lldb thread logging is enabled.
3645 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3646
3647 if (log)
3648 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3649 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3650 return error;
3651}
3652
3653void *
3654NativeProcessLinux::CoordinatorThread (void *arg)
3655{
3656 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3657
3658 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3659 assert (process && "null process passed to CoordinatorThread");
3660 if (!process)
3661 {
3662 if (log)
3663 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3664 return nullptr;
3665 }
3666
3667 // Run the thread state coordinator loop until it is done. This call uses
3668 // efficient waiting for an event to be ready.
3669 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3670 {
3671 }
3672
3673 if (log)
3674 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3675
3676 return nullptr;
3677}
3678
3679void
3680NativeProcessLinux::StopCoordinatorThread()
3681{
3682 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3683 if (log)
3684 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3685
3686 // Tell the coordinator we're done. This will cause the coordinator
3687 // run loop thread to exit when the processing queue hits this message.
3688 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003689 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003690}
3691
Todd Fialaaf245d12014-06-30 21:05:18 +00003692bool
3693NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3694{
3695 for (auto thread_sp : m_threads)
3696 {
3697 assert (thread_sp && "thread list should not contain NULL threads");
3698 if (thread_sp->GetID () == thread_id)
3699 {
3700 // We have this thread.
3701 return true;
3702 }
3703 }
3704
3705 // We don't have this thread.
3706 return false;
3707}
3708
3709NativeThreadProtocolSP
3710NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3711{
3712 // CONSIDER organize threads by map - we can do better than linear.
3713 for (auto thread_sp : m_threads)
3714 {
3715 if (thread_sp->GetID () == thread_id)
3716 return thread_sp;
3717 }
3718
3719 // We don't have this thread.
3720 return NativeThreadProtocolSP ();
3721}
3722
3723bool
3724NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3725{
3726 Mutex::Locker locker (m_threads_mutex);
3727 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3728 {
3729 if (*it && ((*it)->GetID () == thread_id))
3730 {
3731 m_threads.erase (it);
3732 return true;
3733 }
3734 }
3735
3736 // Didn't find it.
3737 return false;
3738}
3739
3740NativeThreadProtocolSP
3741NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3742{
3743 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3744
3745 Mutex::Locker locker (m_threads_mutex);
3746
3747 if (log)
3748 {
3749 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3750 __FUNCTION__,
3751 GetID (),
3752 thread_id);
3753 }
3754
3755 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3756
3757 // If this is the first thread, save it as the current thread
3758 if (m_threads.empty ())
3759 SetCurrentThreadID (thread_id);
3760
3761 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3762 m_threads.push_back (thread_sp);
3763
3764 return thread_sp;
3765}
3766
3767NativeThreadProtocolSP
3768NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3769{
3770 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3771
3772 Mutex::Locker locker (m_threads_mutex);
3773 if (log)
3774 {
3775 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3776 __FUNCTION__,
3777 GetID (),
3778 thread_id);
3779 }
3780
3781 // Retrieve the thread if it is already getting tracked.
3782 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3783 if (thread_sp)
3784 {
3785 if (log)
3786 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3787 __FUNCTION__,
3788 GetID (),
3789 thread_id);
3790 created = false;
3791 return thread_sp;
3792
3793 }
3794
3795 // Create the thread metadata since it isn't being tracked.
3796 if (log)
3797 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3798 __FUNCTION__,
3799 GetID (),
3800 thread_id);
3801
3802 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3803 m_threads.push_back (thread_sp);
3804 created = true;
3805
3806 return thread_sp;
3807}
3808
3809Error
3810NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3811{
Todd Fiala75f47c32014-10-11 21:42:09 +00003812 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003813
3814 Error error;
3815
3816 // Get a linux thread pointer.
3817 if (!thread_sp)
3818 {
3819 error.SetErrorString ("null thread_sp");
3820 if (log)
3821 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3822 return error;
3823 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003824 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003825
3826 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003827 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003828 if (!context_sp)
3829 {
3830 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3831 if (log)
3832 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3833 return error;
3834 }
3835
3836 uint32_t breakpoint_size = 0;
3837 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3838 if (error.Fail ())
3839 {
3840 if (log)
3841 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3842 return error;
3843 }
3844 else
3845 {
3846 if (log)
3847 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3848 }
3849
3850 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3851 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3852 lldb::addr_t breakpoint_addr = initial_pc_addr;
3853 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3854 {
3855 // Do not allow breakpoint probe to wrap around.
3856 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3857 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3858 }
3859
3860 // Check if we stopped because of a breakpoint.
3861 NativeBreakpointSP breakpoint_sp;
3862 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3863 if (!error.Success () || !breakpoint_sp)
3864 {
3865 // We didn't find one at a software probe location. Nothing to do.
3866 if (log)
3867 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3868 return Error ();
3869 }
3870
3871 // If the breakpoint is not a software breakpoint, nothing to do.
3872 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3873 {
3874 if (log)
3875 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3876 return Error ();
3877 }
3878
3879 //
3880 // We have a software breakpoint and need to adjust the PC.
3881 //
3882
3883 // Sanity check.
3884 if (breakpoint_size == 0)
3885 {
3886 // Nothing to do! How did we get here?
3887 if (log)
3888 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);
3889 return Error ();
3890 }
3891
3892 // Change the program counter.
3893 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003894 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 +00003895
3896 error = context_sp->SetPC (breakpoint_addr);
3897 if (error.Fail ())
3898 {
3899 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003900 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 +00003901 return error;
3902 }
3903
3904 return error;
3905}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003906
3907void
3908NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3909{
3910 const bool is_stopped = true;
3911 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3912}
3913
3914void
3915NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3916{
3917 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3918}
3919
3920void
3921NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3922{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003923 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003924}
3925
3926void
3927NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3928 const std::function<void (lldb::tid_t tid)> &call_after_function)
3929{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003930 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3931 if (log)
3932 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3933
Chaoren Linfa03ad22015-02-03 01:50:42 +00003934 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003935 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003936 [=](lldb::tid_t request_stop_tid)
3937 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003938 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003939 },
3940 call_after_function,
3941 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003942}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003943
Chaoren Lin03f12d62015-02-03 01:50:49 +00003944void
3945NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3946 lldb::tid_t skip_stop_request_tid,
3947 const std::function<void (lldb::tid_t tid)> &call_after_function)
3948{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003949 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3950 if (log)
3951 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3952
Chaoren Lin03f12d62015-02-03 01:50:49 +00003953 const lldb::pid_t pid = GetID ();
3954 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3955 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3956 [=](lldb::tid_t request_stop_tid)
3957 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003958 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003959 },
3960 call_after_function,
3961 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003962}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003963
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003964Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003965NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3966{
3967 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3968 if (log)
3969 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3970
3971 Error err;
3972 errno = 0;
3973 if (::tgkill (pid, tid, SIGSTOP) != 0)
3974 {
3975 err.SetErrorToErrno ();
3976 if (log)
3977 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3978 }
3979
3980 return err;
3981}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003982
3983Error
3984NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3985{
3986 char maps_file_name[32];
3987 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3988
3989 FileSpec maps_file_spec(maps_file_name, false);
3990 if (!maps_file_spec.Exists()) {
3991 file_spec.Clear();
3992 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3993 }
3994
3995 FileSpec module_file_spec(module_path, true);
3996
3997 std::ifstream maps_file(maps_file_name);
3998 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3999 StringRef maps_data(maps_data_str.c_str());
4000
4001 while (!maps_data.empty())
4002 {
4003 StringRef maps_row;
4004 std::tie(maps_row, maps_data) = maps_data.split('\n');
4005
4006 SmallVector<StringRef, 16> maps_columns;
4007 maps_row.split(maps_columns, StringRef(" "), -1, false);
4008
4009 if (maps_columns.size() >= 6)
4010 {
4011 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4012 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4013 return Error();
4014 }
4015 }
4016
4017 file_spec.Clear();
4018 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4019 module_file_spec.GetFilename().AsCString(), GetID());
4020}