blob: 410ad53eac0a3c043d412746875b9567cfb35635 [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;
141using namespace llvm;
142
Todd Fialaaf245d12014-06-30 21:05:18 +0000143// Private bits we only need internally.
144namespace
145{
Tamas Berghammer43f2d972015-03-04 11:10:03 +0000146 static void * const EXIT_OPERATION = nullptr;
147
Todd Fialaaf245d12014-06-30 21:05:18 +0000148 const UnixSignals&
149 GetUnixSignals ()
150 {
151 static process_linux::LinuxSignals signals;
152 return signals;
153 }
154
Chaoren Linfa03ad22015-02-03 01:50:42 +0000155 ThreadStateCoordinator::LogFunction
156 GetThreadLoggerFunction ()
157 {
158 return [](const char *format, va_list args)
159 {
160 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
161 if (log)
162 log->VAPrintf (format, args);
163 };
164 }
165
166 void
167 CoordinatorErrorHandler (const std::string &error_message)
168 {
169 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
170 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000171 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000172 assert (false && "ThreadStateCoordinator error reported");
173 }
174
Todd Fialaaf245d12014-06-30 21:05:18 +0000175 Error
176 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
177 {
178 // Grab process info for the running process.
179 ProcessInstanceInfo process_info;
180 if (!platform.GetProcessInfo (pid, process_info))
181 return lldb_private::Error("failed to get process info");
182
183 // Resolve the executable module.
184 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000185 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000186 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
187 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000188 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000189 exe_module_sp,
190 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
191
192 if (!error.Success ())
193 return error;
194
195 // Check if we've got our architecture from the exe_module.
196 arch = exe_module_sp->GetArchitecture ();
197 if (arch.IsValid ())
198 return Error();
199 else
200 return Error("failed to retrieve a valid architecture from the exe module");
201 }
202
203 void
204 DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
205 {
206 uint8_t *ptr = (uint8_t *)bytes;
207 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
208 for(uint32_t i=0; i<loop_count; i++)
209 {
210 s.Printf ("[%x]", *ptr);
211 ptr++;
212 }
213 }
214
215 void
216 PtraceDisplayBytes(int &req, void *data, size_t data_size)
217 {
218 StreamString buf;
219 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
220 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
221
222 if (verbose_log)
223 {
224 switch(req)
225 {
226 case PTRACE_POKETEXT:
227 {
228 DisplayBytes(buf, &data, 8);
229 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
230 break;
231 }
232 case PTRACE_POKEDATA:
233 {
234 DisplayBytes(buf, &data, 8);
235 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
236 break;
237 }
238 case PTRACE_POKEUSER:
239 {
240 DisplayBytes(buf, &data, 8);
241 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
242 break;
243 }
244 case PTRACE_SETREGS:
245 {
246 DisplayBytes(buf, data, data_size);
247 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
248 break;
249 }
250 case PTRACE_SETFPREGS:
251 {
252 DisplayBytes(buf, data, data_size);
253 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
254 break;
255 }
256 case PTRACE_SETSIGINFO:
257 {
258 DisplayBytes(buf, data, sizeof(siginfo_t));
259 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
260 break;
261 }
262 case PTRACE_SETREGSET:
263 {
264 // Extract iov_base from data, which is a pointer to the struct IOVEC
265 DisplayBytes(buf, *(void **)data, data_size);
266 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
267 break;
268 }
269 default:
270 {
271 }
272 }
273 }
274 }
275
276 // Wrapper for ptrace to catch errors and log calls.
277 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
278 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000279 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
280 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000281 {
282 long int result;
283
284 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
285
286 PtraceDisplayBytes(req, data, data_size);
287
Chaoren Lin97ccc292015-02-03 01:51:12 +0000288 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000289 errno = 0;
290 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000291 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000292 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000293 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000294
Chaoren Lin97ccc292015-02-03 01:51:12 +0000295 if (result == -1)
296 error.SetErrorToErrno();
297
Todd Fialaaf245d12014-06-30 21:05:18 +0000298 if (log)
299 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
300 reqName, pid, addr, data, data_size, result, file, line);
301
302 PtraceDisplayBytes(req, data, data_size);
303
Chaoren Lin97ccc292015-02-03 01:51:12 +0000304 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000305 {
306 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000307 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000308 {
309 case ESRCH: str = "ESRCH"; break;
310 case EINVAL: str = "EINVAL"; break;
311 case EBUSY: str = "EBUSY"; break;
312 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000313 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000314 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000315 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000316 }
317
318 return result;
319 }
320
321#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
322 // Wrapper for ptrace when logging is not required.
323 // Sets errno to 0 prior to calling ptrace.
324 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000325 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000326 {
327 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000328
329 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000330 errno = 0;
331 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000332 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000333 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000334 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000335
336 if (result == -1)
337 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000338 return result;
339 }
340#endif
341
342 //------------------------------------------------------------------------------
343 // Static implementations of NativeProcessLinux::ReadMemory and
344 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
345 // functions without needed to go thru the thread funnel.
346
Chaoren Lin97ccc292015-02-03 01:51:12 +0000347 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000348 DoReadMemory (
349 lldb::pid_t pid,
350 lldb::addr_t vm_addr,
351 void *buf,
352 lldb::addr_t size,
353 Error &error)
354 {
355 // ptrace word size is determined by the host, not the child
356 static const unsigned word_size = sizeof(void*);
357 unsigned char *dst = static_cast<unsigned char*>(buf);
358 lldb::addr_t bytes_read;
359 lldb::addr_t remainder;
360 long data;
361
362 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
363 if (log)
364 ProcessPOSIXLog::IncNestLevel();
365 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
366 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
367 pid, word_size, (void*)vm_addr, buf, size);
368
369 assert(sizeof(data) >= word_size);
370 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
371 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000372 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
373 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000374 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 if (log)
376 ProcessPOSIXLog::DecNestLevel();
377 return bytes_read;
378 }
379
380 remainder = size - bytes_read;
381 remainder = remainder > word_size ? word_size : remainder;
382
383 // Copy the data into our buffer
384 for (unsigned i = 0; i < remainder; ++i)
385 dst[i] = ((data >> i*8) & 0xFF);
386
387 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
388 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
389 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
390 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
391 {
392 uintptr_t print_dst = 0;
393 // Format bytes from data by moving into print_dst for log output
394 for (unsigned i = 0; i < remainder; ++i)
395 print_dst |= (((data >> i*8) & 0xFF) << i*8);
396 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
397 (void*)vm_addr, print_dst, (unsigned long)data);
398 }
399
400 vm_addr += word_size;
401 dst += word_size;
402 }
403
404 if (log)
405 ProcessPOSIXLog::DecNestLevel();
406 return bytes_read;
407 }
408
Chaoren Lin97ccc292015-02-03 01:51:12 +0000409 lldb::addr_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000410 DoWriteMemory(
411 lldb::pid_t pid,
412 lldb::addr_t vm_addr,
413 const void *buf,
414 lldb::addr_t size,
415 Error &error)
416 {
417 // ptrace word size is determined by the host, not the child
418 static const unsigned word_size = sizeof(void*);
419 const unsigned char *src = static_cast<const unsigned char*>(buf);
420 lldb::addr_t bytes_written = 0;
421 lldb::addr_t remainder;
422
423 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
424 if (log)
425 ProcessPOSIXLog::IncNestLevel();
426 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
427 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
428 pid, word_size, (void*)vm_addr, buf, size);
429
430 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
431 {
432 remainder = size - bytes_written;
433 remainder = remainder > word_size ? word_size : remainder;
434
435 if (remainder == word_size)
436 {
437 unsigned long data = 0;
438 assert(sizeof(data) >= word_size);
439 for (unsigned i = 0; i < word_size; ++i)
440 data |= (unsigned long)src[i] << i*8;
441
442 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
443 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
445 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
446 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000447 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000448
Chaoren Lin97ccc292015-02-03 01:51:12 +0000449 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000450 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000451 if (log)
452 ProcessPOSIXLog::DecNestLevel();
453 return bytes_written;
454 }
455 }
456 else
457 {
458 unsigned char buff[8];
459 if (DoReadMemory(pid, vm_addr,
460 buff, word_size, error) != word_size)
461 {
462 if (log)
463 ProcessPOSIXLog::DecNestLevel();
464 return bytes_written;
465 }
466
467 memcpy(buff, src, remainder);
468
469 if (DoWriteMemory(pid, vm_addr,
470 buff, word_size, error) != word_size)
471 {
472 if (log)
473 ProcessPOSIXLog::DecNestLevel();
474 return bytes_written;
475 }
476
477 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
478 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
479 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
480 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
481 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000482 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000483 }
484
485 vm_addr += word_size;
486 src += word_size;
487 }
488 if (log)
489 ProcessPOSIXLog::DecNestLevel();
490 return bytes_written;
491 }
492
493 //------------------------------------------------------------------------------
494 /// @class Operation
495 /// @brief Represents a NativeProcessLinux operation.
496 ///
497 /// Under Linux, it is not possible to ptrace() from any other thread but the
498 /// one that spawned or attached to the process from the start. Therefore, when
499 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
500 /// process the operation must be "funneled" to a specific thread to perform the
501 /// task. The Operation class provides an abstract base for all services the
502 /// NativeProcessLinux must perform via the single virtual function Execute, thus
503 /// encapsulating the code that needs to run in the privileged context.
504 class Operation
505 {
506 public:
507 Operation () : m_error() { }
508
509 virtual
510 ~Operation() {}
511
512 virtual void
513 Execute (NativeProcessLinux *process) = 0;
514
515 const Error &
516 GetError () const { return m_error; }
517
518 protected:
519 Error m_error;
520 };
521
522 //------------------------------------------------------------------------------
523 /// @class ReadOperation
524 /// @brief Implements NativeProcessLinux::ReadMemory.
525 class ReadOperation : public Operation
526 {
527 public:
528 ReadOperation (
529 lldb::addr_t addr,
530 void *buff,
531 lldb::addr_t size,
Todd Fialab35103e2014-07-10 05:25:39 +0000532 lldb::addr_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000533 Operation (),
534 m_addr (addr),
535 m_buff (buff),
536 m_size (size),
537 m_result (result)
538 {
539 }
540
541 void Execute (NativeProcessLinux *process) override;
542
543 private:
544 lldb::addr_t m_addr;
545 void *m_buff;
546 lldb::addr_t m_size;
547 lldb::addr_t &m_result;
548 };
549
550 void
551 ReadOperation::Execute (NativeProcessLinux *process)
552 {
553 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
554 }
555
556 //------------------------------------------------------------------------------
557 /// @class WriteOperation
558 /// @brief Implements NativeProcessLinux::WriteMemory.
559 class WriteOperation : public Operation
560 {
561 public:
562 WriteOperation (
563 lldb::addr_t addr,
564 const void *buff,
565 lldb::addr_t size,
566 lldb::addr_t &result) :
567 Operation (),
568 m_addr (addr),
569 m_buff (buff),
570 m_size (size),
571 m_result (result)
572 {
573 }
574
575 void Execute (NativeProcessLinux *process) override;
576
577 private:
578 lldb::addr_t m_addr;
579 const void *m_buff;
580 lldb::addr_t m_size;
581 lldb::addr_t &m_result;
582 };
583
584 void
585 WriteOperation::Execute(NativeProcessLinux *process)
586 {
587 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
588 }
589
590 //------------------------------------------------------------------------------
591 /// @class ReadRegOperation
592 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
593 class ReadRegOperation : public Operation
594 {
595 public:
596 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000597 RegisterValue &value)
598 : m_tid(tid),
599 m_offset(static_cast<uintptr_t> (offset)),
600 m_reg_name(reg_name),
601 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000602 { }
603
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000604 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000605
606 private:
607 lldb::tid_t m_tid;
608 uintptr_t m_offset;
609 const char *m_reg_name;
610 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000611 };
612
613 void
614 ReadRegOperation::Execute(NativeProcessLinux *monitor)
615 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000616#if defined (__arm64__) || defined (__aarch64__)
617 if (m_offset > sizeof(struct user_pt_regs))
618 {
619 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
620 if (offset > sizeof(struct user_fpsimd_state))
621 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000622 m_error.SetErrorString("invalid offset value");
623 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000624 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000625 elf_fpregset_t regs;
626 int regset = NT_FPREGSET;
627 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000628
Chaoren Lin97ccc292015-02-03 01:51:12 +0000629 ioVec.iov_base = &regs;
630 ioVec.iov_len = sizeof regs;
631 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
632 if (m_error.Success())
633 {
634 lldb_private::ArchSpec arch;
635 if (monitor->GetArchitecture(arch))
636 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000637 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000638 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000639 }
640 }
641 else
642 {
643 elf_gregset_t regs;
644 int regset = NT_PRSTATUS;
645 struct iovec ioVec;
646
647 ioVec.iov_base = &regs;
648 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000649 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
650 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000651 {
652 lldb_private::ArchSpec arch;
653 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000654 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000655 else
656 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000657 }
658 }
659#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000660 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
661
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000662 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 +0000663 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000664 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000665
Todd Fialaaf245d12014-06-30 21:05:18 +0000666 if (log)
667 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
668 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000669#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000670 }
671
672 //------------------------------------------------------------------------------
673 /// @class WriteRegOperation
674 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
675 class WriteRegOperation : public Operation
676 {
677 public:
678 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000679 const RegisterValue &value)
680 : m_tid(tid),
681 m_offset(offset),
682 m_reg_name(reg_name),
683 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000684 { }
685
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000686 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000687
688 private:
689 lldb::tid_t m_tid;
690 uintptr_t m_offset;
691 const char *m_reg_name;
692 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000693 };
694
695 void
696 WriteRegOperation::Execute(NativeProcessLinux *monitor)
697 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000698#if defined (__arm64__) || defined (__aarch64__)
699 if (m_offset > sizeof(struct user_pt_regs))
700 {
701 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
702 if (offset > sizeof(struct user_fpsimd_state))
703 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000704 m_error.SetErrorString("invalid offset value");
705 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000706 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000707 elf_fpregset_t regs;
708 int regset = NT_FPREGSET;
709 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000710
Chaoren Lin97ccc292015-02-03 01:51:12 +0000711 ioVec.iov_base = &regs;
712 ioVec.iov_len = sizeof regs;
713 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000714 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000715 {
716 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
717 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000718 }
719 }
720 else
721 {
722 elf_gregset_t regs;
723 int regset = NT_PRSTATUS;
724 struct iovec ioVec;
725
726 ioVec.iov_base = &regs;
727 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000728 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000729 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000730 {
731 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000732 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000733 }
734 }
735#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000736 void* buf;
737 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
738
739 buf = (void*) m_value.GetAsUInt64();
740
741 if (log)
742 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000743 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000744#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000745 }
746
747 //------------------------------------------------------------------------------
748 /// @class ReadGPROperation
749 /// @brief Implements NativeProcessLinux::ReadGPR.
750 class ReadGPROperation : public Operation
751 {
752 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000753 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
754 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000755 { }
756
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000757 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000758
759 private:
760 lldb::tid_t m_tid;
761 void *m_buf;
762 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000763 };
764
765 void
766 ReadGPROperation::Execute(NativeProcessLinux *monitor)
767 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000768#if defined (__arm64__) || defined (__aarch64__)
769 int regset = NT_PRSTATUS;
770 struct iovec ioVec;
771
772 ioVec.iov_base = m_buf;
773 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000774 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000775#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000776 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000777#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000778 }
779
780 //------------------------------------------------------------------------------
781 /// @class ReadFPROperation
782 /// @brief Implements NativeProcessLinux::ReadFPR.
783 class ReadFPROperation : public Operation
784 {
785 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000786 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
787 : m_tid(tid),
788 m_buf(buf),
789 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000790 { }
791
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000792 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000793
794 private:
795 lldb::tid_t m_tid;
796 void *m_buf;
797 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 };
799
800 void
801 ReadFPROperation::Execute(NativeProcessLinux *monitor)
802 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000803#if defined (__arm64__) || defined (__aarch64__)
804 int regset = NT_FPREGSET;
805 struct iovec ioVec;
806
807 ioVec.iov_base = m_buf;
808 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000809 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000810#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000811 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000812#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000813 }
814
815 //------------------------------------------------------------------------------
816 /// @class ReadRegisterSetOperation
817 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
818 class ReadRegisterSetOperation : public Operation
819 {
820 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000821 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
822 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000823 { }
824
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000825 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000826
827 private:
828 lldb::tid_t m_tid;
829 void *m_buf;
830 size_t m_buf_size;
831 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000832 };
833
834 void
835 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
836 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000837 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000838 }
839
840 //------------------------------------------------------------------------------
841 /// @class WriteGPROperation
842 /// @brief Implements NativeProcessLinux::WriteGPR.
843 class WriteGPROperation : public Operation
844 {
845 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000846 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
847 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000848 { }
849
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000850 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000851
852 private:
853 lldb::tid_t m_tid;
854 void *m_buf;
855 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000856 };
857
858 void
859 WriteGPROperation::Execute(NativeProcessLinux *monitor)
860 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000861#if defined (__arm64__) || defined (__aarch64__)
862 int regset = NT_PRSTATUS;
863 struct iovec ioVec;
864
865 ioVec.iov_base = m_buf;
866 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000867 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000868#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000869 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000870#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000871 }
872
873 //------------------------------------------------------------------------------
874 /// @class WriteFPROperation
875 /// @brief Implements NativeProcessLinux::WriteFPR.
876 class WriteFPROperation : public Operation
877 {
878 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000879 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
880 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000881 { }
882
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000883 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000884
885 private:
886 lldb::tid_t m_tid;
887 void *m_buf;
888 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000889 };
890
891 void
892 WriteFPROperation::Execute(NativeProcessLinux *monitor)
893 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000894#if defined (__arm64__) || defined (__aarch64__)
895 int regset = NT_FPREGSET;
896 struct iovec ioVec;
897
898 ioVec.iov_base = m_buf;
899 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000900 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000901#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000902 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000903#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000904 }
905
906 //------------------------------------------------------------------------------
907 /// @class WriteRegisterSetOperation
908 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
909 class WriteRegisterSetOperation : public Operation
910 {
911 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000912 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
913 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000914 { }
915
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000916 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000917
918 private:
919 lldb::tid_t m_tid;
920 void *m_buf;
921 size_t m_buf_size;
922 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000923 };
924
925 void
926 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
927 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000928 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000929 }
930
931 //------------------------------------------------------------------------------
932 /// @class ResumeOperation
933 /// @brief Implements NativeProcessLinux::Resume.
934 class ResumeOperation : public Operation
935 {
936 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000937 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
938 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000939
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000940 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000941
942 private:
943 lldb::tid_t m_tid;
944 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000945 };
946
947 void
948 ResumeOperation::Execute(NativeProcessLinux *monitor)
949 {
950 intptr_t data = 0;
951
952 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
953 data = m_signo;
954
Chaoren Lin97ccc292015-02-03 01:51:12 +0000955 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
956 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000957 {
958 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
959
960 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000961 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000962 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 }
964
965 //------------------------------------------------------------------------------
966 /// @class SingleStepOperation
967 /// @brief Implements NativeProcessLinux::SingleStep.
968 class SingleStepOperation : public Operation
969 {
970 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000971 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
972 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000973
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000974 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000975
976 private:
977 lldb::tid_t m_tid;
978 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000979 };
980
981 void
982 SingleStepOperation::Execute(NativeProcessLinux *monitor)
983 {
984 intptr_t data = 0;
985
986 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
987 data = m_signo;
988
Chaoren Lin97ccc292015-02-03 01:51:12 +0000989 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000990 }
991
992 //------------------------------------------------------------------------------
993 /// @class SiginfoOperation
994 /// @brief Implements NativeProcessLinux::GetSignalInfo.
995 class SiginfoOperation : public Operation
996 {
997 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000998 SiginfoOperation(lldb::tid_t tid, void *info)
999 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001000
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001001 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001002
1003 private:
1004 lldb::tid_t m_tid;
1005 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001006 };
1007
1008 void
1009 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1010 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001011 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001012 }
1013
1014 //------------------------------------------------------------------------------
1015 /// @class EventMessageOperation
1016 /// @brief Implements NativeProcessLinux::GetEventMessage.
1017 class EventMessageOperation : public Operation
1018 {
1019 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001020 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1021 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001022
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001023 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001024
1025 private:
1026 lldb::tid_t m_tid;
1027 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001028 };
1029
1030 void
1031 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1032 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001033 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001034 }
1035
1036 class DetachOperation : public Operation
1037 {
1038 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001039 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001040
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001041 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001042
1043 private:
1044 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001045 };
1046
1047 void
1048 DetachOperation::Execute(NativeProcessLinux *monitor)
1049 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001050 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001051 }
1052
1053}
1054
Todd Fialaaf245d12014-06-30 21:05:18 +00001055// Simple helper function to ensure flags are enabled on the given file
1056// descriptor.
1057static bool
1058EnsureFDFlags(int fd, int flags, Error &error)
1059{
1060 int status;
1061
1062 if ((status = fcntl(fd, F_GETFL)) == -1)
1063 {
1064 error.SetErrorToErrno();
1065 return false;
1066 }
1067
1068 if (fcntl(fd, F_SETFL, status | flags) == -1)
1069 {
1070 error.SetErrorToErrno();
1071 return false;
1072 }
1073
1074 return true;
1075}
1076
1077NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1078 : m_monitor(monitor)
1079{
1080 sem_init(&m_semaphore, 0, 0);
1081}
1082
1083NativeProcessLinux::OperationArgs::~OperationArgs()
1084{
1085 sem_destroy(&m_semaphore);
1086}
1087
1088NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
1089 lldb_private::Module *module,
1090 char const **argv,
1091 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001092 const std::string &stdin_path,
1093 const std::string &stdout_path,
1094 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001095 const char *working_dir,
1096 const lldb_private::ProcessLaunchInfo &launch_info)
Todd Fialaaf245d12014-06-30 21:05:18 +00001097 : OperationArgs(monitor),
1098 m_module(module),
1099 m_argv(argv),
1100 m_envp(envp),
1101 m_stdin_path(stdin_path),
1102 m_stdout_path(stdout_path),
1103 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001104 m_working_dir(working_dir),
1105 m_launch_info(launch_info)
1106{
1107}
Todd Fialaaf245d12014-06-30 21:05:18 +00001108
1109NativeProcessLinux::LaunchArgs::~LaunchArgs()
1110{ }
1111
1112NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1113 lldb::pid_t pid)
1114 : OperationArgs(monitor), m_pid(pid) { }
1115
1116NativeProcessLinux::AttachArgs::~AttachArgs()
1117{ }
1118
1119// -----------------------------------------------------------------------------
1120// Public Static Methods
1121// -----------------------------------------------------------------------------
1122
1123lldb_private::Error
1124NativeProcessLinux::LaunchProcess (
1125 lldb_private::Module *exe_module,
1126 lldb_private::ProcessLaunchInfo &launch_info,
1127 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1128 NativeProcessProtocolSP &native_process_sp)
1129{
1130 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1131
1132 Error error;
1133
1134 // Verify the working directory is valid if one was specified.
1135 const char* working_dir = launch_info.GetWorkingDirectory ();
1136 if (working_dir)
1137 {
1138 FileSpec working_dir_fs (working_dir, true);
1139 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1140 {
1141 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1142 return error;
1143 }
1144 }
1145
Zachary Turner696b5282014-08-14 16:01:25 +00001146 const lldb_private::FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001147
1148 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001149 std::string stdin_path;
1150 std::string stdout_path;
1151 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001152
1153 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001154 if (file_action)
1155 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001156
1157 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001158 if (file_action)
1159 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001160
1161 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001162 if (file_action)
1163 stderr_path = file_action->GetPath ();
1164
1165 if (log)
1166 {
1167 if (!stdin_path.empty ())
1168 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1169 else
1170 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1171
1172 if (!stdout_path.empty ())
1173 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1174 else
1175 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1176
1177 if (!stderr_path.empty ())
1178 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1179 else
1180 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1181 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001182
1183 // Create the NativeProcessLinux in launch mode.
1184 native_process_sp.reset (new NativeProcessLinux ());
1185
1186 if (log)
1187 {
1188 int i = 0;
1189 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1190 {
1191 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1192 ++i;
1193 }
1194 }
1195
1196 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1197 {
1198 native_process_sp.reset ();
1199 error.SetErrorStringWithFormat ("failed to register the native delegate");
1200 return error;
1201 }
1202
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001203 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001204 exe_module,
1205 launch_info.GetArguments ().GetConstArgumentVector (),
1206 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1207 stdin_path,
1208 stdout_path,
1209 stderr_path,
1210 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001211 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001212 error);
1213
1214 if (error.Fail ())
1215 {
1216 native_process_sp.reset ();
1217 if (log)
1218 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1219 return error;
1220 }
1221
1222 launch_info.SetProcessID (native_process_sp->GetID ());
1223
1224 return error;
1225}
1226
1227lldb_private::Error
1228NativeProcessLinux::AttachToProcess (
1229 lldb::pid_t pid,
1230 lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
1231 NativeProcessProtocolSP &native_process_sp)
1232{
1233 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1234 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1235 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1236
1237 // Grab the current platform architecture. This should be Linux,
1238 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001239 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001240 if (!platform_sp)
1241 return Error("failed to get a valid default platform");
1242
1243 // Retrieve the architecture for the running process.
1244 ArchSpec process_arch;
1245 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1246 if (!error.Success ())
1247 return error;
1248
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001249 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001250
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001251 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001252 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001253 error.SetErrorStringWithFormat ("failed to register the native delegate");
1254 return error;
1255 }
1256
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001257 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001258 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001260
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001261 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001262 return error;
1263}
1264
1265// -----------------------------------------------------------------------------
1266// Public Instance Methods
1267// -----------------------------------------------------------------------------
1268
1269NativeProcessLinux::NativeProcessLinux () :
1270 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1271 m_arch (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001272 m_operation_thread (),
1273 m_monitor_thread (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001274 m_operation (nullptr),
1275 m_operation_mutex (),
1276 m_operation_pending (),
1277 m_operation_done (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001278 m_supports_mem_region (eLazyBoolCalculate),
1279 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001280 m_mem_region_cache_mutex (),
1281 m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1282 m_coordinator_thread ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001283{
1284}
1285
1286//------------------------------------------------------------------------------
1287/// The basic design of the NativeProcessLinux is built around two threads.
1288///
1289/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1290/// for changes in the debugee state. When a change is detected a
1291/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1292/// "drives" state changes in the debugger.
1293///
1294/// The second thread (@see OperationThread) is responsible for two things 1)
1295/// launching or attaching to the inferior process, and then 2) servicing
1296/// operations such as register reads/writes, stepping, etc. See the comments
1297/// on the Operation class for more info as to why this is needed.
1298void
1299NativeProcessLinux::LaunchInferior (
1300 Module *module,
1301 const char *argv[],
1302 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001303 const std::string &stdin_path,
1304 const std::string &stdout_path,
1305 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001306 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001307 const lldb_private::ProcessLaunchInfo &launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001308 lldb_private::Error &error)
1309{
1310 if (module)
1311 m_arch = module->GetArchitecture ();
1312
Chaoren Linfa03ad22015-02-03 01:50:42 +00001313 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001314
1315 std::unique_ptr<LaunchArgs> args(
1316 new LaunchArgs(
1317 this, module, argv, envp,
1318 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001319 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001320
Chaoren Linfa03ad22015-02-03 01:50:42 +00001321 sem_init (&m_operation_pending, 0, 0);
1322 sem_init (&m_operation_done, 0, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001323
Chaoren Linfa03ad22015-02-03 01:50:42 +00001324 StartLaunchOpThread (args.get(), error);
1325 if (!error.Success ())
1326 return;
1327
1328 error = StartCoordinatorThread ();
1329 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001330 return;
1331
1332WAIT_AGAIN:
1333 // Wait for the operation thread to initialize.
1334 if (sem_wait(&args->m_semaphore))
1335 {
1336 if (errno == EINTR)
1337 goto WAIT_AGAIN;
1338 else
1339 {
1340 error.SetErrorToErrno();
1341 return;
1342 }
1343 }
1344
1345 // Check that the launch was a success.
1346 if (!args->m_error.Success())
1347 {
1348 StopOpThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001349 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001350 error = args->m_error;
1351 return;
1352 }
1353
1354 // Finally, start monitoring the child process for change in state.
1355 m_monitor_thread = Host::StartMonitoringChildProcess(
1356 NativeProcessLinux::MonitorCallback, this, GetID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001357 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001358 {
1359 error.SetErrorToGenericError();
1360 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1361 return;
1362 }
1363}
1364
1365void
1366NativeProcessLinux::AttachToInferior (lldb::pid_t pid, lldb_private::Error &error)
1367{
1368 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1369 if (log)
1370 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1371
1372 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001373 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001374 if (!platform_sp)
1375 {
1376 if (log)
1377 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1378 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001379 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001380 }
1381
1382 // Gather info about the process.
1383 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001384 if (!platform_sp->GetProcessInfo (pid, process_info))
1385 {
1386 if (log)
1387 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1388 error.SetErrorString ("failed to get process info");
1389 return;
1390 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001391
1392 // Resolve the executable module
1393 ModuleSP exe_module_sp;
1394 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001395 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001396 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001397 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001398 if (!error.Success())
1399 return;
1400
1401 // Set the architecture to the exe architecture.
1402 m_arch = exe_module_sp->GetArchitecture();
1403 if (log)
1404 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1405
1406 m_pid = pid;
1407 SetState(eStateAttaching);
1408
1409 sem_init (&m_operation_pending, 0, 0);
1410 sem_init (&m_operation_done, 0, 0);
1411
1412 std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1413
1414 StartAttachOpThread(args.get (), error);
1415 if (!error.Success ())
1416 return;
1417
Chaoren Linfa03ad22015-02-03 01:50:42 +00001418 error = StartCoordinatorThread ();
1419 if (!error.Success ())
1420 return;
1421
Todd Fialaaf245d12014-06-30 21:05:18 +00001422WAIT_AGAIN:
1423 // Wait for the operation thread to initialize.
1424 if (sem_wait (&args->m_semaphore))
1425 {
1426 if (errno == EINTR)
1427 goto WAIT_AGAIN;
1428 else
1429 {
1430 error.SetErrorToErrno ();
1431 return;
1432 }
1433 }
1434
1435 // Check that the attach was a success.
1436 if (!args->m_error.Success ())
1437 {
1438 StopOpThread ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001439 StopCoordinatorThread ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001440 error = args->m_error;
1441 return;
1442 }
1443
1444 // Finally, start monitoring the child process for change in state.
1445 m_monitor_thread = Host::StartMonitoringChildProcess (
1446 NativeProcessLinux::MonitorCallback, this, GetID (), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001447 if (!m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001448 {
1449 error.SetErrorToGenericError ();
1450 error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1451 return;
1452 }
1453}
1454
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001455void
1456NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001457{
1458 StopMonitor();
1459}
1460
1461//------------------------------------------------------------------------------
1462// Thread setup and tear down.
1463
1464void
1465NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1466{
1467 static const char *g_thread_name = "lldb.process.nativelinux.operation";
1468
Zachary Turneracee96a2014-09-23 18:32:09 +00001469 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001470 return;
1471
Zachary Turner39de3112014-09-09 20:54:56 +00001472 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001473}
1474
1475void *
1476NativeProcessLinux::LaunchOpThread(void *arg)
1477{
1478 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1479
1480 if (!Launch(args)) {
1481 sem_post(&args->m_semaphore);
1482 return NULL;
1483 }
1484
1485 ServeOperation(args);
1486 return NULL;
1487}
1488
1489bool
1490NativeProcessLinux::Launch(LaunchArgs *args)
1491{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001492 assert (args && "null args");
1493 if (!args)
1494 return false;
1495
Todd Fialaaf245d12014-06-30 21:05:18 +00001496 NativeProcessLinux *monitor = args->m_monitor;
1497 assert (monitor && "monitor is NULL");
Todd Fialaaf245d12014-06-30 21:05:18 +00001498
1499 const char **argv = args->m_argv;
1500 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001501 const char *working_dir = args->m_working_dir;
1502
1503 lldb_utility::PseudoTerminal terminal;
1504 const size_t err_len = 1024;
1505 char err_str[err_len];
1506 lldb::pid_t pid;
1507 NativeThreadProtocolSP thread_sp;
1508
1509 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001510
1511 // Propagate the environment if one is not supplied.
1512 if (envp == NULL || envp[0] == NULL)
1513 envp = const_cast<const char **>(environ);
1514
1515 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1516 {
1517 args->m_error.SetErrorToGenericError();
1518 args->m_error.SetErrorString("Process fork failed.");
Todd Fiala75f47c32014-10-11 21:42:09 +00001519 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001520 }
1521
1522 // Recognized child exit status codes.
1523 enum {
1524 ePtraceFailed = 1,
1525 eDupStdinFailed,
1526 eDupStdoutFailed,
1527 eDupStderrFailed,
1528 eChdirFailed,
1529 eExecFailed,
1530 eSetGidFailed
1531 };
1532
1533 // Child process.
1534 if (pid == 0)
1535 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001536 // FIXME consider opening a pipe between parent/child and have this forked child
1537 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001538
Todd Fiala75f47c32014-10-11 21:42:09 +00001539 // Start tracing this child that is about to exec.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001540 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1541 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001542 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001543
Pavel Labath493c3a12015-02-04 10:36:57 +00001544 // terminal has already dupped the tty descriptors to stdin/out/err.
1545 // This closes original fd from which they were copied (and avoids
1546 // leaking descriptors to the debugged process.
1547 terminal.CloseSlaveFileDescriptor();
1548
Todd Fialaaf245d12014-06-30 21:05:18 +00001549 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001550 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001551 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001552
1553 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001554 if (setpgid(0, 0) != 0)
1555 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001556 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001557 // Don't allow this to prevent an inferior exec.
1558 }
1559
1560 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001561 if (!args->m_stdin_path.empty ())
1562 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001563 exit(eDupStdinFailed);
1564
Todd Fiala75f47c32014-10-11 21:42:09 +00001565 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001566 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001567 exit(eDupStdoutFailed);
1568
Todd Fiala75f47c32014-10-11 21:42:09 +00001569 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001570 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 exit(eDupStderrFailed);
1572
1573 // Change working directory
1574 if (working_dir != NULL && working_dir[0])
1575 if (0 != ::chdir(working_dir))
1576 exit(eChdirFailed);
1577
Todd Fiala0bce1b62014-08-17 00:10:50 +00001578 // Disable ASLR if requested.
1579 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1580 {
1581 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1582 if (old_personality == -1)
1583 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001584 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001585 }
1586 else
1587 {
1588 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1589 if (new_personality == -1)
1590 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001591 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001592 }
1593 else
1594 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001595 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001596 }
1597 }
1598 }
1599
Todd Fiala75f47c32014-10-11 21:42:09 +00001600 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001601 execve(argv[0],
1602 const_cast<char *const *>(argv),
1603 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001604
1605 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001606 exit(eExecFailed);
1607 }
1608
Todd Fiala75f47c32014-10-11 21:42:09 +00001609 //
1610 // This is the parent code here.
1611 //
1612 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1613
Todd Fialaaf245d12014-06-30 21:05:18 +00001614 // Wait for the child process to trap on its call to execve.
1615 ::pid_t wpid;
1616 int status;
1617 if ((wpid = waitpid(pid, &status, 0)) < 0)
1618 {
1619 args->m_error.SetErrorToErrno();
1620
1621 if (log)
1622 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1623
1624 // Mark the inferior as invalid.
1625 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1626 monitor->SetState (StateType::eStateInvalid);
1627
Todd Fiala75f47c32014-10-11 21:42:09 +00001628 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001629 }
1630 else if (WIFEXITED(status))
1631 {
1632 // open, dup or execve likely failed for some reason.
1633 args->m_error.SetErrorToGenericError();
1634 switch (WEXITSTATUS(status))
1635 {
1636 case ePtraceFailed:
1637 args->m_error.SetErrorString("Child ptrace failed.");
1638 break;
1639 case eDupStdinFailed:
1640 args->m_error.SetErrorString("Child open stdin failed.");
1641 break;
1642 case eDupStdoutFailed:
1643 args->m_error.SetErrorString("Child open stdout failed.");
1644 break;
1645 case eDupStderrFailed:
1646 args->m_error.SetErrorString("Child open stderr failed.");
1647 break;
1648 case eChdirFailed:
1649 args->m_error.SetErrorString("Child failed to set working directory.");
1650 break;
1651 case eExecFailed:
1652 args->m_error.SetErrorString("Child exec failed.");
1653 break;
1654 case eSetGidFailed:
1655 args->m_error.SetErrorString("Child setgid failed.");
1656 break;
1657 default:
1658 args->m_error.SetErrorString("Child returned unknown exit status.");
1659 break;
1660 }
1661
1662 if (log)
1663 {
1664 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1665 __FUNCTION__,
1666 WEXITSTATUS(status));
1667 }
1668
1669 // Mark the inferior as invalid.
1670 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1671 monitor->SetState (StateType::eStateInvalid);
1672
Todd Fiala75f47c32014-10-11 21:42:09 +00001673 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001674 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001675 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001676 "Could not sync with inferior process.");
1677
1678 if (log)
1679 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1680
Chaoren Lin97ccc292015-02-03 01:51:12 +00001681 args->m_error = SetDefaultPtraceOpts(pid);
1682 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001683 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001684 if (log)
1685 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1686 __FUNCTION__,
1687 args->m_error.AsCString ());
1688
1689 // Mark the inferior as invalid.
1690 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1691 monitor->SetState (StateType::eStateInvalid);
1692
Todd Fiala75f47c32014-10-11 21:42:09 +00001693 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 }
1695
1696 // Release the master terminal descriptor and pass it off to the
1697 // NativeProcessLinux instance. Similarly stash the inferior pid.
1698 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1699 monitor->m_pid = pid;
1700
1701 // Set the terminal fd to be in non blocking mode (it simplifies the
1702 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1703 // descriptor to read from).
1704 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1705 {
1706 if (log)
1707 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1708 __FUNCTION__,
1709 args->m_error.AsCString ());
1710
1711 // Mark the inferior as invalid.
1712 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
1713 monitor->SetState (StateType::eStateInvalid);
1714
Todd Fiala75f47c32014-10-11 21:42:09 +00001715 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001716 }
1717
1718 if (log)
1719 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1720
Chaoren Linfa03ad22015-02-03 01:50:42 +00001721 thread_sp = monitor->AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001722 assert (thread_sp && "AddThread() returned a nullptr thread");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001723 monitor->NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001724 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001725
1726 // Let our process instance know the thread has stopped.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001727 monitor->SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001728 monitor->SetState (StateType::eStateStopped);
1729
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 if (log)
1731 {
1732 if (args->m_error.Success ())
1733 {
1734 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1735 }
1736 else
1737 {
1738 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1739 __FUNCTION__,
1740 args->m_error.AsCString ());
1741 }
1742 }
1743 return args->m_error.Success();
1744}
1745
1746void
1747NativeProcessLinux::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1748{
1749 static const char *g_thread_name = "lldb.process.linux.operation";
1750
Zachary Turneracee96a2014-09-23 18:32:09 +00001751 if (m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00001752 return;
1753
Zachary Turner39de3112014-09-09 20:54:56 +00001754 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001755}
1756
1757void *
1758NativeProcessLinux::AttachOpThread(void *arg)
1759{
1760 AttachArgs *args = static_cast<AttachArgs*>(arg);
1761
1762 if (!Attach(args)) {
1763 sem_post(&args->m_semaphore);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001764 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 }
1766
1767 ServeOperation(args);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001768 return nullptr;
Todd Fialaaf245d12014-06-30 21:05:18 +00001769}
1770
1771bool
1772NativeProcessLinux::Attach(AttachArgs *args)
1773{
1774 lldb::pid_t pid = args->m_pid;
1775
1776 NativeProcessLinux *monitor = args->m_monitor;
1777 lldb::ThreadSP inferior;
1778 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1779
1780 // Use a map to keep track of the threads which we have attached/need to attach.
1781 Host::TidMap tids_to_attach;
1782 if (pid <= 1)
1783 {
1784 args->m_error.SetErrorToGenericError();
1785 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1786 goto FINISH;
1787 }
1788
1789 while (Host::FindProcessThreads(pid, tids_to_attach))
1790 {
1791 for (Host::TidMap::iterator it = tids_to_attach.begin();
1792 it != tids_to_attach.end();)
1793 {
1794 if (it->second == false)
1795 {
1796 lldb::tid_t tid = it->first;
1797
1798 // Attach to the requested process.
1799 // An attach will cause the thread to stop with a SIGSTOP.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001800 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
1801 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001802 {
1803 // No such thread. The thread may have exited.
1804 // More error handling may be needed.
Chaoren Lin97ccc292015-02-03 01:51:12 +00001805 if (args->m_error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001806 {
1807 it = tids_to_attach.erase(it);
1808 continue;
1809 }
1810 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001811 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001812 }
1813
1814 int status;
1815 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1816 // At this point we should have a thread stopped if waitpid succeeds.
1817 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1818 {
1819 // No such thread. The thread may have exited.
1820 // More error handling may be needed.
1821 if (errno == ESRCH)
1822 {
1823 it = tids_to_attach.erase(it);
1824 continue;
1825 }
1826 else
1827 {
1828 args->m_error.SetErrorToErrno();
1829 goto FINISH;
1830 }
1831 }
1832
Chaoren Lin97ccc292015-02-03 01:51:12 +00001833 args->m_error = SetDefaultPtraceOpts(tid);
1834 if (args->m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001835 goto FINISH;
Todd Fialaaf245d12014-06-30 21:05:18 +00001836
1837
1838 if (log)
1839 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1840
1841 it->second = true;
1842
1843 // Create the thread, mark it as stopped.
1844 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1845 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001846
1847 // This will notify this is a new thread and tell the system it is stopped.
1848 monitor->NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001849 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001850 monitor->SetCurrentThreadID (thread_sp->GetID ());
1851 }
1852
1853 // move the loop forward
1854 ++it;
1855 }
1856 }
1857
1858 if (tids_to_attach.size() > 0)
1859 {
1860 monitor->m_pid = pid;
1861 // Let our process instance know the thread has stopped.
1862 monitor->SetState (StateType::eStateStopped);
1863 }
1864 else
1865 {
1866 args->m_error.SetErrorToGenericError();
1867 args->m_error.SetErrorString("No such process.");
1868 }
1869
1870 FINISH:
1871 return args->m_error.Success();
1872}
1873
Chaoren Lin97ccc292015-02-03 01:51:12 +00001874Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001875NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1876{
1877 long ptrace_opts = 0;
1878
1879 // Have the child raise an event on exit. This is used to keep the child in
1880 // limbo until it is destroyed.
1881 ptrace_opts |= PTRACE_O_TRACEEXIT;
1882
1883 // Have the tracer trace threads which spawn in the inferior process.
1884 // TODO: if we want to support tracing the inferiors' child, add the
1885 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1886 ptrace_opts |= PTRACE_O_TRACECLONE;
1887
1888 // Have the tracer notify us before execve returns
1889 // (needed to disable legacy SIGTRAP generation)
1890 ptrace_opts |= PTRACE_O_TRACEEXEC;
1891
Chaoren Lin97ccc292015-02-03 01:51:12 +00001892 Error error;
1893 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
1894 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001895}
1896
1897static ExitType convert_pid_status_to_exit_type (int status)
1898{
1899 if (WIFEXITED (status))
1900 return ExitType::eExitTypeExit;
1901 else if (WIFSIGNALED (status))
1902 return ExitType::eExitTypeSignal;
1903 else if (WIFSTOPPED (status))
1904 return ExitType::eExitTypeStop;
1905 else
1906 {
1907 // We don't know what this is.
1908 return ExitType::eExitTypeInvalid;
1909 }
1910}
1911
1912static int convert_pid_status_to_return_code (int status)
1913{
1914 if (WIFEXITED (status))
1915 return WEXITSTATUS (status);
1916 else if (WIFSIGNALED (status))
1917 return WTERMSIG (status);
1918 else if (WIFSTOPPED (status))
1919 return WSTOPSIG (status);
1920 else
1921 {
1922 // We don't know what this is.
1923 return ExitType::eExitTypeInvalid;
1924 }
1925}
1926
1927// Main process monitoring waitpid-loop handler.
1928bool
1929NativeProcessLinux::MonitorCallback(void *callback_baton,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001930 lldb::pid_t pid,
1931 bool exited,
1932 int signal,
1933 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001934{
1935 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1936
1937 NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1938 assert (process && "process is null");
1939 if (!process)
1940 {
1941 if (log)
1942 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1943 return true;
1944 }
1945
1946 // Certain activities differ based on whether the pid is the tid of the main thread.
1947 const bool is_main_thread = (pid == process->GetID ());
1948
1949 // Assume we keep monitoring by default.
1950 bool stop_monitoring = false;
1951
1952 // Handle when the thread exits.
1953 if (exited)
1954 {
1955 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001956 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 +00001957
1958 // This is a thread that exited. Ensure we're not tracking it anymore.
1959 const bool thread_found = process->StopTrackingThread (pid);
1960
Chaoren Linfa03ad22015-02-03 01:50:42 +00001961 // Make sure the thread state coordinator knows about this.
1962 process->NotifyThreadDeath (pid);
1963
Todd Fialaaf245d12014-06-30 21:05:18 +00001964 if (is_main_thread)
1965 {
1966 // We only set the exit status and notify the delegate if we haven't already set the process
1967 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1968 // for the main thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001969 const bool already_notified = (process->GetState() == StateType::eStateExited) || (process->GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001970 if (!already_notified)
1971 {
1972 if (log)
1973 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 ()));
1974 // The main thread exited. We're done monitoring. Report to delegate.
1975 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1976
1977 // Notify delegate that our process has exited.
1978 process->SetState (StateType::eStateExited, true);
1979 }
1980 else
1981 {
1982 if (log)
1983 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1984 }
1985 return true;
1986 }
1987 else
1988 {
1989 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1990 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1991 // and we would have done an all-stop then.
1992 if (log)
1993 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1994
1995 // Not the main thread, we keep going.
1996 return false;
1997 }
1998 }
1999
2000 // Get details on the signal raised.
2001 siginfo_t info;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002002 const auto err = process->GetSignalInfo(pid, &info);
2003 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002004 {
2005 // We have retrieved the signal info. Dispatch appropriately.
2006 if (info.si_signo == SIGTRAP)
2007 process->MonitorSIGTRAP(&info, pid);
2008 else
2009 process->MonitorSignal(&info, pid, exited);
2010
2011 stop_monitoring = false;
2012 }
2013 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002014 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002015 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002016 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002017 // This is a group stop reception for this tid.
2018 if (log)
2019 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, process->GetID (), pid);
2020 process->NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002021 }
2022 else
2023 {
2024 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2025
2026 // A return value of ESRCH means the thread/process is no longer on the system,
2027 // so it was killed somehow outside of our control. Either way, we can't do anything
2028 // with it anymore.
2029
2030 // We stop monitoring if it was the main thread.
2031 stop_monitoring = is_main_thread;
2032
2033 // Stop tracking the metadata for the thread since it's entirely off the system now.
2034 const bool thread_found = process->StopTrackingThread (pid);
2035
Chaoren Linfa03ad22015-02-03 01:50:42 +00002036 // Make sure the thread state coordinator knows about this.
2037 process->NotifyThreadDeath (pid);
2038
Todd Fialaaf245d12014-06-30 21:05:18 +00002039 if (log)
2040 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002041 __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 +00002042
2043 if (is_main_thread)
2044 {
2045 // Notify the delegate - our process is not available but appears to have been killed outside
2046 // our control. Is eStateExited the right exit state in this case?
2047 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2048 process->SetState (StateType::eStateExited, true);
2049 }
2050 else
2051 {
2052 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2053 if (log)
2054 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);
2055 }
2056 }
2057 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002058
2059 return stop_monitoring;
2060}
2061
2062void
2063NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2064{
2065 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2066 const bool is_main_thread = (pid == GetID ());
2067
2068 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2069 if (!info)
2070 return;
2071
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002072 Mutex::Locker locker (m_threads_mutex);
2073
Todd Fialaaf245d12014-06-30 21:05:18 +00002074 // See if we can find a thread for this signal.
2075 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2076 if (!thread_sp)
2077 {
2078 if (log)
2079 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2080 }
2081
2082 switch (info->si_code)
2083 {
2084 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2085 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2086 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2087
2088 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2089 {
2090 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2091
Chaoren Linfa03ad22015-02-03 01:50:42 +00002092 // The main thread is stopped here.
2093 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002094 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002095 NotifyThreadStop (pid);
2096
Todd Fialaaf245d12014-06-30 21:05:18 +00002097 unsigned long event_message = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002098 if (GetEventMessage (pid, &event_message).Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002099 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002100 tid = static_cast<lldb::tid_t> (event_message);
2101 if (log)
2102 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002103
Chaoren Linfa03ad22015-02-03 01:50:42 +00002104 // If we don't track the thread yet: create it, mark as stopped.
2105 // If we do track it, this is the wait we needed. Now resume the new thread.
2106 // In all cases, resume the current (i.e. main process) thread.
2107 bool created_now = false;
2108 NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2109 assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2110
2111 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2112 if (!created_now)
2113 {
2114 // We can now resume the newly created thread since it is fully created.
2115 NotifyThreadCreateStopped (tid);
2116 m_coordinator_up->RequestThreadResume (tid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002117 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002118 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002119 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002120 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002121 },
2122 CoordinatorErrorHandler);
2123 }
2124 else
2125 {
2126 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2127 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002128 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetLaunching ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002129 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002130 }
2131 else
2132 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002133 if (log)
2134 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 +00002135 }
2136
2137 // In all cases, we can resume the main thread here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002138 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002139 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002140 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002141 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002142 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002143 },
2144 CoordinatorErrorHandler);
2145
Todd Fialaaf245d12014-06-30 21:05:18 +00002146 break;
2147 }
2148
2149 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002150 {
2151 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002152 if (log)
2153 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002154
Chaoren Linfa03ad22015-02-03 01:50:42 +00002155 // The thread state coordinator needs to reset due to the exec.
2156 m_coordinator_up->ResetForExec ();
2157
2158 // 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 +00002159 if (log)
2160 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2161
2162 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002163 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002164 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2165 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002166 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002167 main_thread_sp = thread_sp;
2168 if (log)
2169 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002170 }
2171 else
2172 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002173 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002174 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002175 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002176 }
2177 }
2178
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002179 m_threads.clear ();
2180
2181 if (main_thread_sp)
2182 {
2183 m_threads.push_back (main_thread_sp);
2184 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002185 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002186 }
2187 else
2188 {
2189 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2190 if (log)
2191 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2192 }
2193
Chaoren Linfa03ad22015-02-03 01:50:42 +00002194 // Tell coordinator about about the "new" (since exec) stopped main thread.
2195 const lldb::tid_t main_thread_tid = GetID ();
2196 NotifyThreadCreateStopped (main_thread_tid);
2197
2198 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2199 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002200 // Let our delegate know we have just exec'd.
2201 NotifyDidExec ();
2202
2203 // If we have a main thread, indicate we are stopped.
2204 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002205
2206 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002207 CallAfterRunningThreadsStop (pid,
2208 [=] (lldb::tid_t signaling_tid)
2209 {
2210 SetState (StateType::eStateStopped, true);
2211 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002212
Todd Fialaaf245d12014-06-30 21:05:18 +00002213 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002214 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002215
2216 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2217 {
2218 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002219
2220 // This thread is currently stopped. It's not actually dead yet, just about to be.
2221 NotifyThreadStop (pid);
2222
Todd Fialaaf245d12014-06-30 21:05:18 +00002223 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002224 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002225 data = -1;
2226
2227 if (log)
2228 {
2229 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2230 __FUNCTION__,
2231 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2232 pid,
2233 is_main_thread ? "is main thread" : "not main thread");
2234 }
2235
Todd Fialaaf245d12014-06-30 21:05:18 +00002236 if (is_main_thread)
2237 {
2238 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002239 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002240
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002241 const int signo = static_cast<int> (data);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002242 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002243 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002244 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002245 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002246 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002247 },
2248 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002249
2250 break;
2251 }
2252
2253 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002254 case TRAP_TRACE: // We receive this on single stepping.
2255 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002256 if (thread_sp)
2257 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002258 // If a watchpoint was hit, report it
2259 uint32_t wp_index;
2260 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2261 if (error.Fail() && log)
2262 log->Printf("NativeProcessLinux::%s() "
2263 "received error while checking for watchpoint hits, "
2264 "pid = %" PRIu64 " error = %s",
2265 __FUNCTION__, pid, error.AsCString());
2266 if (wp_index != LLDB_INVALID_INDEX32)
2267 {
2268 MonitorWatchpoint(pid, thread_sp, wp_index);
2269 break;
2270 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002271 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002272 // Otherwise, report step over
2273 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002274 break;
2275
2276 case SI_KERNEL:
2277 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002278 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002279 break;
2280
2281 case SIGTRAP:
2282 case (SIGTRAP | 0x80):
2283 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002284 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2285
2286 // This thread is currently stopped.
2287 NotifyThreadStop (pid);
2288 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002289 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002290
2291
Todd Fialaaf245d12014-06-30 21:05:18 +00002292 // Ignore these signals until we know more about them.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002293 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002294 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002295 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002296 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002297 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002298 },
2299 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002300 break;
2301
2302 default:
2303 assert(false && "Unexpected SIGTRAP code!");
2304 if (log)
2305 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)));
2306 break;
2307
2308 }
2309}
2310
2311void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002312NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2313{
2314 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2315 if (log)
2316 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2317 __FUNCTION__, pid);
2318
2319 if (thread_sp)
2320 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2321
2322 // This thread is currently stopped.
2323 NotifyThreadStop(pid);
2324
2325 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2326 // This would have already happened at the time the Resume() with step operation was signaled.
2327 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2328 // once all running threads have checked in as stopped.
2329 SetCurrentThreadID(pid);
2330 // Tell the process we have a stop (from software breakpoint).
2331 CallAfterRunningThreadsStop(pid,
2332 [=](lldb::tid_t signaling_tid)
2333 {
2334 SetState(StateType::eStateStopped, true);
2335 });
2336}
2337
2338void
2339NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2340{
2341 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2342 if (log)
2343 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2344 __FUNCTION__, pid);
2345
2346 // This thread is currently stopped.
2347 NotifyThreadStop(pid);
2348
2349 // Mark the thread as stopped at breakpoint.
2350 if (thread_sp)
2351 {
2352 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2353 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2354 if (error.Fail())
2355 if (log)
2356 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2357 __FUNCTION__, pid, error.AsCString());
2358 }
2359 else
2360 if (log)
2361 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2362 "warning, cannot process software breakpoint since no thread metadata",
2363 __FUNCTION__, pid);
2364
2365
2366 // We need to tell all other running threads before we notify the delegate about this stop.
2367 CallAfterRunningThreadsStop(pid,
2368 [=](lldb::tid_t deferred_notification_tid)
2369 {
2370 SetCurrentThreadID(deferred_notification_tid);
2371 // Tell the process we have a stop (from software breakpoint).
2372 SetState(StateType::eStateStopped, true);
2373 });
2374}
2375
2376void
2377NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2378{
2379 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2380 if (log)
2381 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2382 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2383 __FUNCTION__, pid, wp_index);
2384
2385 // This thread is currently stopped.
2386 NotifyThreadStop(pid);
2387
2388 // Mark the thread as stopped at watchpoint.
2389 // The address is at (lldb::addr_t)info->si_addr if we need it.
2390 lldbassert(thread_sp && "thread_sp cannot be NULL");
2391 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2392
2393 // We need to tell all other running threads before we notify the delegate about this stop.
2394 CallAfterRunningThreadsStop(pid,
2395 [=](lldb::tid_t deferred_notification_tid)
2396 {
2397 SetCurrentThreadID(deferred_notification_tid);
2398 // Tell the process we have a stop (from watchpoint).
2399 SetState(StateType::eStateStopped, true);
2400 });
2401}
2402
2403void
Todd Fialaaf245d12014-06-30 21:05:18 +00002404NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2405{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002406 assert (info && "null info");
2407 if (!info)
2408 return;
2409
2410 const int signo = info->si_signo;
2411 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002412
2413 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2414
2415 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2416 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2417 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2418 //
2419 // IOW, user generated signals never generate what we consider to be a
2420 // "crash".
2421 //
2422 // Similarly, ACK signals generated by this monitor.
2423
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002424 Mutex::Locker locker (m_threads_mutex);
2425
Todd Fialaaf245d12014-06-30 21:05:18 +00002426 // See if we can find a thread for this signal.
2427 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2428 if (!thread_sp)
2429 {
2430 if (log)
2431 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2432 }
2433
2434 // Handle the signal.
2435 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2436 {
2437 if (log)
2438 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2439 __FUNCTION__,
2440 GetUnixSignals ().GetSignalAsCString (signo),
2441 signo,
2442 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2443 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002444 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002445 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002446 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002447
Todd Fiala58a2f662014-08-12 17:02:07 +00002448 // Check for new thread notification.
2449 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2450 {
2451 // A new thread creation is being signaled. This is one of two parts that come in
2452 // a non-deterministic order. pid is the thread id.
2453 if (log)
2454 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2455 __FUNCTION__, GetID (), pid);
2456
2457 // Did we already create the thread?
Todd Fiala511e5cd2014-09-11 23:29:14 +00002458 bool created_now = false;
2459 thread_sp = GetOrCreateThread (pid, created_now);
Todd Fiala58a2f662014-08-12 17:02:07 +00002460 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2461
2462 // 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 +00002463 if (!created_now)
Todd Fialaaf245d12014-06-30 21:05:18 +00002464 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002465 // We can now resume the newly created thread since it is fully created.
2466 NotifyThreadCreateStopped (pid);
2467 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002468 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002469 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002470 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Lin37c768c2015-02-03 01:51:30 +00002471 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002472 },
2473 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002474 }
2475 else
2476 {
Todd Fiala58a2f662014-08-12 17:02:07 +00002477 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before
2478 // this thread is ready to go.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002479 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetLaunching ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002480 }
2481
Todd Fiala58a2f662014-08-12 17:02:07 +00002482 // Done handling.
2483 return;
2484 }
2485
2486 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002487 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002488 {
2489 // This is a tgkill()-based stop.
2490 if (thread_sp)
2491 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002492 if (log)
2493 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2494 __FUNCTION__,
2495 GetID (),
2496 pid);
2497
Chaoren Linaab58632015-02-03 01:50:57 +00002498 // Check that we're not already marked with a stop reason.
2499 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2500 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2501 // and that, without an intervening resume, we received another stop. It is more likely
2502 // that we are missing the marking of a run state somewhere if we find that the thread was
2503 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002504 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2505 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002506
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002507 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002508 if (!StateIsStoppedState (thread_state, false))
2509 {
2510 // An inferior thread just stopped, but was not the primary cause of the process stop.
2511 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2512 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002513 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002514 SetCurrentThreadID (thread_sp->GetID ());
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002515 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002516 }
2517 else
2518 {
2519 if (log)
2520 {
2521 // Retrieve the signal name if the thread was stopped by a signal.
2522 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002523 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002524 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2525 if (!signal_name)
2526 signal_name = "<no-signal-name>";
2527
2528 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",
2529 __FUNCTION__,
2530 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002531 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002532 StateAsCString (thread_state),
2533 stop_signo,
2534 signal_name);
2535 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002536 // Tell the thread state coordinator about the stop.
2537 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002538 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002539 }
2540
2541 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002542 return;
2543 }
2544
2545 if (log)
2546 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2547
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002548 // This thread is stopped.
2549 NotifyThreadStop (pid);
2550
Todd Fialaaf245d12014-06-30 21:05:18 +00002551 switch (signo)
2552 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002553 case SIGSTOP:
2554 {
2555 if (log)
2556 {
2557 if (is_from_llgs)
2558 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2559 else
2560 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2561 }
2562
Chaoren Linfa03ad22015-02-03 01:50:42 +00002563 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2564 // This thread will get stopped again as part of the group-stop completion.
2565 m_coordinator_up->RequestThreadResume (pid,
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002566 [=](lldb::tid_t tid_to_resume, bool supress_signal)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002567 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002568 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002569 // Pass this signal number on to the inferior to handle.
Chaoren Lin37c768c2015-02-03 01:51:30 +00002570 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002571 },
2572 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002573 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002574 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002575 case SIGSEGV:
2576 case SIGILL:
2577 case SIGFPE:
2578 case SIGBUS:
2579 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002580 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002581 break;
2582 default:
2583 // This is just a pre-signal-delivery notification of the incoming signal.
2584 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002585 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002586
2587 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002588 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002589
2590 // Send a stop to the debugger after we get all other threads to stop.
2591 CallAfterRunningThreadsStop (pid,
2592 [=] (lldb::tid_t signaling_tid)
2593 {
2594 SetCurrentThreadID (signaling_tid);
2595 SetState (StateType::eStateStopped, true);
2596 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002597}
2598
2599Error
2600NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2601{
Todd Fialaaf245d12014-06-30 21:05:18 +00002602 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2603 if (log)
2604 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2605
Chaoren Lin03f12d62015-02-03 01:50:49 +00002606 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2607 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002608 int deferred_signo = 0;
2609 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002610 bool stepping = false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002611
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002612 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002613
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002614 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002615 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002616 assert (thread_sp && "thread list should not contain NULL threads");
2617
2618 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2619
2620 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002621 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002622 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002623 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2624 __FUNCTION__, GetID (), thread_sp->GetID ());
2625 continue;
2626 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002627
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002628 if (log)
2629 {
2630 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2631 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2632 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002633
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002634 switch (action->state)
2635 {
2636 case eStateRunning:
2637 {
2638 // Run the thread, possibly feeding it the signal.
2639 const int signo = action->signal;
2640 m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2641 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2642 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002643 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002644 // Pass this signal number on to the inferior to handle.
2645 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2646 if (resume_result.Success())
2647 SetState(eStateRunning, true);
2648 return resume_result;
2649 },
2650 CoordinatorErrorHandler);
2651 break;
2652 }
2653
2654 case eStateStepping:
2655 {
2656 // Request the step.
2657 const int signo = action->signal;
2658 m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2659 [=](lldb::tid_t tid_to_step, bool supress_signal)
2660 {
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002661 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002662 const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2663 assert (step_result.Success() && "SingleStep() failed");
2664 if (step_result.Success())
2665 SetState(eStateStepping, true);
2666 return step_result;
2667 },
2668 CoordinatorErrorHandler);
2669 stepping = true;
2670 break;
2671 }
2672
2673 case eStateSuspended:
2674 case eStateStopped:
2675 // if we haven't chosen a deferred signal tid yet, use this one.
2676 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00002677 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002678 deferred_signal_tid = thread_sp->GetID ();
2679 deferred_signal_thread_sp = thread_sp;
2680 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00002681 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002682 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002683
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002684 default:
2685 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2686 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002687 }
2688 }
2689
Chaoren Linfa03ad22015-02-03 01:50:42 +00002690 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2691 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002692 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2693 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00002694 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00002695 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2696 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00002697 [=](lldb::tid_t deferred_notification_tid)
2698 {
Chaoren Linae29d392015-02-03 01:50:46 +00002699 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002700 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00002701
2702 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002703 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00002704
2705 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002706 SetState (StateType::eStateStopped, true);
2707 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002708 }
2709
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002710 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002711}
2712
2713Error
2714NativeProcessLinux::Halt ()
2715{
2716 Error error;
2717
Todd Fialaaf245d12014-06-30 21:05:18 +00002718 if (kill (GetID (), SIGSTOP) != 0)
2719 error.SetErrorToErrno ();
2720
2721 return error;
2722}
2723
2724Error
2725NativeProcessLinux::Detach ()
2726{
2727 Error error;
2728
2729 // Tell ptrace to detach from the process.
2730 if (GetID () != LLDB_INVALID_PROCESS_ID)
2731 error = Detach (GetID ());
2732
2733 // Stop monitoring the inferior.
2734 StopMonitor ();
2735
2736 // No error.
2737 return error;
2738}
2739
2740Error
2741NativeProcessLinux::Signal (int signo)
2742{
2743 Error error;
2744
2745 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2746 if (log)
2747 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2748 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2749
2750 if (kill(GetID(), signo))
2751 error.SetErrorToErrno();
2752
2753 return error;
2754}
2755
2756Error
Chaoren Line9547b82015-02-03 01:51:00 +00002757NativeProcessLinux::Interrupt ()
2758{
2759 // Pick a running thread (or if none, a not-dead stopped thread) as
2760 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002761 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2762
2763 NativeThreadProtocolSP running_thread_sp;
2764 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002765
2766 if (log)
2767 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2768
2769 Mutex::Locker locker (m_threads_mutex);
2770
2771 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002772 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002773 // The thread shouldn't be null but lets just cover that here.
2774 if (!thread_sp)
2775 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002776
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002777 // If we have a running or stepping thread, we'll call that the
2778 // target of the interrupt.
2779 const auto thread_state = thread_sp->GetState ();
2780 if (thread_state == eStateRunning ||
2781 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002782 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002783 running_thread_sp = thread_sp;
2784 break;
2785 }
2786 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2787 {
2788 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2789 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002790 }
2791 }
2792
2793 if (!running_thread_sp && !stopped_thread_sp)
2794 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002795 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002796 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002797 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002798
Chaoren Line9547b82015-02-03 01:51:00 +00002799 return error;
2800 }
2801
2802 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2803
2804 if (log)
2805 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2806 __FUNCTION__,
2807 GetID (),
2808 running_thread_sp ? "running" : "stopped",
2809 deferred_signal_thread_sp->GetID ());
2810
2811 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
2812 [=](lldb::tid_t deferred_notification_tid)
2813 {
2814 // Set the signal thread to the current thread.
2815 SetCurrentThreadID (deferred_notification_tid);
2816
2817 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002818 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00002819
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002820 // Tell the process delegate that the process is in a stopped state.
2821 SetState (StateType::eStateStopped, true);
2822 });
2823 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002824}
2825
2826Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002827NativeProcessLinux::Kill ()
2828{
2829 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2830 if (log)
2831 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2832
2833 Error error;
2834
2835 switch (m_state)
2836 {
2837 case StateType::eStateInvalid:
2838 case StateType::eStateExited:
2839 case StateType::eStateCrashed:
2840 case StateType::eStateDetached:
2841 case StateType::eStateUnloaded:
2842 // Nothing to do - the process is already dead.
2843 if (log)
2844 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2845 return error;
2846
2847 case StateType::eStateConnected:
2848 case StateType::eStateAttaching:
2849 case StateType::eStateLaunching:
2850 case StateType::eStateStopped:
2851 case StateType::eStateRunning:
2852 case StateType::eStateStepping:
2853 case StateType::eStateSuspended:
2854 // We can try to kill a process in these states.
2855 break;
2856 }
2857
2858 if (kill (GetID (), SIGKILL) != 0)
2859 {
2860 error.SetErrorToErrno ();
2861 return error;
2862 }
2863
2864 return error;
2865}
2866
2867static Error
2868ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2869{
2870 memory_region_info.Clear();
2871
2872 StringExtractor line_extractor (maps_line.c_str ());
2873
2874 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2875 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2876
2877 // Parse out the starting address
2878 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2879
2880 // Parse out hyphen separating start and end address from range.
2881 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2882 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2883
2884 // Parse out the ending address
2885 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2886
2887 // Parse out the space after the address.
2888 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2889 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2890
2891 // Save the range.
2892 memory_region_info.GetRange ().SetRangeBase (start_address);
2893 memory_region_info.GetRange ().SetRangeEnd (end_address);
2894
2895 // Parse out each permission entry.
2896 if (line_extractor.GetBytesLeft () < 4)
2897 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2898
2899 // Handle read permission.
2900 const char read_perm_char = line_extractor.GetChar ();
2901 if (read_perm_char == 'r')
2902 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2903 else
2904 {
2905 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2906 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2907 }
2908
2909 // Handle write permission.
2910 const char write_perm_char = line_extractor.GetChar ();
2911 if (write_perm_char == 'w')
2912 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2913 else
2914 {
2915 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2916 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2917 }
2918
2919 // Handle execute permission.
2920 const char exec_perm_char = line_extractor.GetChar ();
2921 if (exec_perm_char == 'x')
2922 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2923 else
2924 {
2925 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2926 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2927 }
2928
2929 return Error ();
2930}
2931
2932Error
2933NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2934{
2935 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2936 // with no perms if it is not mapped.
2937
2938 // Use an approach that reads memory regions from /proc/{pid}/maps.
2939 // Assume proc maps entries are in ascending order.
2940 // FIXME assert if we find differently.
2941 Mutex::Locker locker (m_mem_region_cache_mutex);
2942
2943 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2944 Error error;
2945
2946 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2947 {
2948 // We're done.
2949 error.SetErrorString ("unsupported");
2950 return error;
2951 }
2952
2953 // If our cache is empty, pull the latest. There should always be at least one memory region
2954 // if memory region handling is supported.
2955 if (m_mem_region_cache.empty ())
2956 {
2957 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2958 [&] (const std::string &line) -> bool
2959 {
2960 MemoryRegionInfo info;
2961 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2962 if (parse_error.Success ())
2963 {
2964 m_mem_region_cache.push_back (info);
2965 return true;
2966 }
2967 else
2968 {
2969 if (log)
2970 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2971 return false;
2972 }
2973 });
2974
2975 // If we had an error, we'll mark unsupported.
2976 if (error.Fail ())
2977 {
2978 m_supports_mem_region = LazyBool::eLazyBoolNo;
2979 return error;
2980 }
2981 else if (m_mem_region_cache.empty ())
2982 {
2983 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2984 // is supported. Assume we don't support map entries via procfs.
2985 if (log)
2986 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2987 m_supports_mem_region = LazyBool::eLazyBoolNo;
2988 error.SetErrorString ("not supported");
2989 return error;
2990 }
2991
2992 if (log)
2993 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2994
2995 // We support memory retrieval, remember that.
2996 m_supports_mem_region = LazyBool::eLazyBoolYes;
2997 }
2998 else
2999 {
3000 if (log)
3001 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3002 }
3003
3004 lldb::addr_t prev_base_address = 0;
3005
3006 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3007 // There can be a ton of regions on pthreads apps with lots of threads.
3008 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3009 {
3010 MemoryRegionInfo &proc_entry_info = *it;
3011
3012 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3013 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3014 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3015
3016 // If the target address comes before this entry, indicate distance to next region.
3017 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3018 {
3019 range_info.GetRange ().SetRangeBase (load_addr);
3020 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3021 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3022 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3023 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3024
3025 return error;
3026 }
3027 else if (proc_entry_info.GetRange ().Contains (load_addr))
3028 {
3029 // The target address is within the memory region we're processing here.
3030 range_info = proc_entry_info;
3031 return error;
3032 }
3033
3034 // The target memory address comes somewhere after the region we just parsed.
3035 }
3036
3037 // If we made it here, we didn't find an entry that contained the given address.
3038 error.SetErrorString ("address comes after final region");
3039
3040 if (log)
3041 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3042
3043 return error;
3044}
3045
3046void
3047NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3048{
3049 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3050 if (log)
3051 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3052
3053 {
3054 Mutex::Locker locker (m_mem_region_cache_mutex);
3055 if (log)
3056 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3057 m_mem_region_cache.clear ();
3058 }
3059}
3060
3061Error
3062NativeProcessLinux::AllocateMemory (
3063 lldb::addr_t size,
3064 uint32_t permissions,
3065 lldb::addr_t &addr)
3066{
3067 // FIXME implementing this requires the equivalent of
3068 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3069 // functional ThreadPlans working with Native*Protocol.
3070#if 1
3071 return Error ("not implemented yet");
3072#else
3073 addr = LLDB_INVALID_ADDRESS;
3074
3075 unsigned prot = 0;
3076 if (permissions & lldb::ePermissionsReadable)
3077 prot |= eMmapProtRead;
3078 if (permissions & lldb::ePermissionsWritable)
3079 prot |= eMmapProtWrite;
3080 if (permissions & lldb::ePermissionsExecutable)
3081 prot |= eMmapProtExec;
3082
3083 // TODO implement this directly in NativeProcessLinux
3084 // (and lift to NativeProcessPOSIX if/when that class is
3085 // refactored out).
3086 if (InferiorCallMmap(this, addr, 0, size, prot,
3087 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3088 m_addr_to_mmap_size[addr] = size;
3089 return Error ();
3090 } else {
3091 addr = LLDB_INVALID_ADDRESS;
3092 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3093 }
3094#endif
3095}
3096
3097Error
3098NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3099{
3100 // FIXME see comments in AllocateMemory - required lower-level
3101 // bits not in place yet (ThreadPlans)
3102 return Error ("not implemented");
3103}
3104
3105lldb::addr_t
3106NativeProcessLinux::GetSharedLibraryInfoAddress ()
3107{
3108#if 1
3109 // punt on this for now
3110 return LLDB_INVALID_ADDRESS;
3111#else
3112 // Return the image info address for the exe module
3113#if 1
3114 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3115
3116 ModuleSP module_sp;
3117 Error error = GetExeModuleSP (module_sp);
3118 if (error.Fail ())
3119 {
3120 if (log)
3121 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3122 return LLDB_INVALID_ADDRESS;
3123 }
3124
3125 if (module_sp == nullptr)
3126 {
3127 if (log)
3128 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3129 return LLDB_INVALID_ADDRESS;
3130 }
3131
3132 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3133 if (object_file_sp == nullptr)
3134 {
3135 if (log)
3136 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3137 return LLDB_INVALID_ADDRESS;
3138 }
3139
3140 return obj_file_sp->GetImageInfoAddress();
3141#else
3142 Target *target = &GetTarget();
3143 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3144 Address addr = obj_file->GetImageInfoAddress(target);
3145
3146 if (addr.IsValid())
3147 return addr.GetLoadAddress(target);
3148 return LLDB_INVALID_ADDRESS;
3149#endif
3150#endif // punt on this for now
3151}
3152
3153size_t
3154NativeProcessLinux::UpdateThreads ()
3155{
3156 // The NativeProcessLinux monitoring threads are always up to date
3157 // with respect to thread state and they keep the thread list
3158 // populated properly. All this method needs to do is return the
3159 // thread count.
3160 Mutex::Locker locker (m_threads_mutex);
3161 return m_threads.size ();
3162}
3163
3164bool
3165NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3166{
3167 arch = m_arch;
3168 return true;
3169}
3170
3171Error
3172NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3173{
3174 // FIXME put this behind a breakpoint protocol class that can be
3175 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003176 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003177 static const uint8_t g_i386_opcode [] = { 0xCC };
3178
3179 switch (m_arch.GetMachine ())
3180 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003181 case llvm::Triple::aarch64:
3182 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3183 return Error ();
3184
Todd Fialaaf245d12014-06-30 21:05:18 +00003185 case llvm::Triple::x86:
3186 case llvm::Triple::x86_64:
3187 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3188 return Error ();
3189
3190 default:
3191 assert(false && "CPU type not supported!");
3192 return Error ("CPU type not supported");
3193 }
3194}
3195
3196Error
3197NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3198{
3199 if (hardware)
3200 return Error ("NativeProcessLinux does not support hardware breakpoints");
3201 else
3202 return SetSoftwareBreakpoint (addr, size);
3203}
3204
3205Error
3206NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3207{
3208 // FIXME put this behind a breakpoint protocol class that can be
3209 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003210 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003211 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003212 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003213
3214 switch (m_arch.GetMachine ())
3215 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003216 case llvm::Triple::aarch64:
3217 trap_opcode_bytes = g_aarch64_opcode;
3218 actual_opcode_size = sizeof(g_aarch64_opcode);
3219 return Error ();
3220
Todd Fialaaf245d12014-06-30 21:05:18 +00003221 case llvm::Triple::x86:
3222 case llvm::Triple::x86_64:
3223 trap_opcode_bytes = g_i386_opcode;
3224 actual_opcode_size = sizeof(g_i386_opcode);
3225 return Error ();
3226
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003227 case llvm::Triple::mips64:
3228 case llvm::Triple::mips64el:
3229 trap_opcode_bytes = g_mips64_opcode;
3230 actual_opcode_size = sizeof(g_mips64_opcode);
3231 return Error ();
3232
Todd Fialaaf245d12014-06-30 21:05:18 +00003233 default:
3234 assert(false && "CPU type not supported!");
3235 return Error ("CPU type not supported");
3236 }
3237}
3238
3239#if 0
3240ProcessMessage::CrashReason
3241NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3242{
3243 ProcessMessage::CrashReason reason;
3244 assert(info->si_signo == SIGSEGV);
3245
3246 reason = ProcessMessage::eInvalidCrashReason;
3247
3248 switch (info->si_code)
3249 {
3250 default:
3251 assert(false && "unexpected si_code for SIGSEGV");
3252 break;
3253 case SI_KERNEL:
3254 // Linux will occasionally send spurious SI_KERNEL codes.
3255 // (this is poorly documented in sigaction)
3256 // One way to get this is via unaligned SIMD loads.
3257 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3258 break;
3259 case SEGV_MAPERR:
3260 reason = ProcessMessage::eInvalidAddress;
3261 break;
3262 case SEGV_ACCERR:
3263 reason = ProcessMessage::ePrivilegedAddress;
3264 break;
3265 }
3266
3267 return reason;
3268}
3269#endif
3270
3271
3272#if 0
3273ProcessMessage::CrashReason
3274NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3275{
3276 ProcessMessage::CrashReason reason;
3277 assert(info->si_signo == SIGILL);
3278
3279 reason = ProcessMessage::eInvalidCrashReason;
3280
3281 switch (info->si_code)
3282 {
3283 default:
3284 assert(false && "unexpected si_code for SIGILL");
3285 break;
3286 case ILL_ILLOPC:
3287 reason = ProcessMessage::eIllegalOpcode;
3288 break;
3289 case ILL_ILLOPN:
3290 reason = ProcessMessage::eIllegalOperand;
3291 break;
3292 case ILL_ILLADR:
3293 reason = ProcessMessage::eIllegalAddressingMode;
3294 break;
3295 case ILL_ILLTRP:
3296 reason = ProcessMessage::eIllegalTrap;
3297 break;
3298 case ILL_PRVOPC:
3299 reason = ProcessMessage::ePrivilegedOpcode;
3300 break;
3301 case ILL_PRVREG:
3302 reason = ProcessMessage::ePrivilegedRegister;
3303 break;
3304 case ILL_COPROC:
3305 reason = ProcessMessage::eCoprocessorError;
3306 break;
3307 case ILL_BADSTK:
3308 reason = ProcessMessage::eInternalStackError;
3309 break;
3310 }
3311
3312 return reason;
3313}
3314#endif
3315
3316#if 0
3317ProcessMessage::CrashReason
3318NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3319{
3320 ProcessMessage::CrashReason reason;
3321 assert(info->si_signo == SIGFPE);
3322
3323 reason = ProcessMessage::eInvalidCrashReason;
3324
3325 switch (info->si_code)
3326 {
3327 default:
3328 assert(false && "unexpected si_code for SIGFPE");
3329 break;
3330 case FPE_INTDIV:
3331 reason = ProcessMessage::eIntegerDivideByZero;
3332 break;
3333 case FPE_INTOVF:
3334 reason = ProcessMessage::eIntegerOverflow;
3335 break;
3336 case FPE_FLTDIV:
3337 reason = ProcessMessage::eFloatDivideByZero;
3338 break;
3339 case FPE_FLTOVF:
3340 reason = ProcessMessage::eFloatOverflow;
3341 break;
3342 case FPE_FLTUND:
3343 reason = ProcessMessage::eFloatUnderflow;
3344 break;
3345 case FPE_FLTRES:
3346 reason = ProcessMessage::eFloatInexactResult;
3347 break;
3348 case FPE_FLTINV:
3349 reason = ProcessMessage::eFloatInvalidOperation;
3350 break;
3351 case FPE_FLTSUB:
3352 reason = ProcessMessage::eFloatSubscriptRange;
3353 break;
3354 }
3355
3356 return reason;
3357}
3358#endif
3359
3360#if 0
3361ProcessMessage::CrashReason
3362NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3363{
3364 ProcessMessage::CrashReason reason;
3365 assert(info->si_signo == SIGBUS);
3366
3367 reason = ProcessMessage::eInvalidCrashReason;
3368
3369 switch (info->si_code)
3370 {
3371 default:
3372 assert(false && "unexpected si_code for SIGBUS");
3373 break;
3374 case BUS_ADRALN:
3375 reason = ProcessMessage::eIllegalAlignment;
3376 break;
3377 case BUS_ADRERR:
3378 reason = ProcessMessage::eIllegalAddress;
3379 break;
3380 case BUS_OBJERR:
3381 reason = ProcessMessage::eHardwareError;
3382 break;
3383 }
3384
3385 return reason;
3386}
3387#endif
3388
3389void
3390NativeProcessLinux::ServeOperation(OperationArgs *args)
3391{
3392 NativeProcessLinux *monitor = args->m_monitor;
3393
3394 // We are finised with the arguments and are ready to go. Sync with the
3395 // parent thread and start serving operations on the inferior.
3396 sem_post(&args->m_semaphore);
3397
3398 for(;;)
3399 {
3400 // wait for next pending operation
3401 if (sem_wait(&monitor->m_operation_pending))
3402 {
3403 if (errno == EINTR)
3404 continue;
3405 assert(false && "Unexpected errno from sem_wait");
3406 }
3407
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003408 // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3409 // android. We don't have to send a post to the m_operation_done semaphore because in this
3410 // case the synchronization is achieved by a Join() call
3411 if (monitor->m_operation == EXIT_OPERATION)
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003412 break;
Tamas Berghammer6806fde2015-03-02 11:04:03 +00003413
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003414 static_cast<Operation*>(monitor->m_operation)->Execute(monitor);
Todd Fialaaf245d12014-06-30 21:05:18 +00003415
3416 // notify calling thread that operation is complete
3417 sem_post(&monitor->m_operation_done);
3418 }
3419}
3420
3421void
3422NativeProcessLinux::DoOperation(void *op)
3423{
3424 Mutex::Locker lock(m_operation_mutex);
3425
3426 m_operation = op;
3427
3428 // notify operation thread that an operation is ready to be processed
3429 sem_post(&m_operation_pending);
3430
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003431 // Don't wait for the operation to complete in case of an exit operation. The operation thread
3432 // will exit without posting to the semaphore
3433 if (m_operation == EXIT_OPERATION)
3434 return;
3435
Todd Fialaaf245d12014-06-30 21:05:18 +00003436 // wait for operation to complete
3437 while (sem_wait(&m_operation_done))
3438 {
3439 if (errno == EINTR)
3440 continue;
3441 assert(false && "Unexpected errno from sem_wait");
3442 }
3443}
3444
3445Error
3446NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3447{
3448 ReadOperation op(addr, buf, size, bytes_read);
3449 DoOperation(&op);
3450 return op.GetError ();
3451}
3452
3453Error
3454NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3455{
3456 WriteOperation op(addr, buf, size, bytes_written);
3457 DoOperation(&op);
3458 return op.GetError ();
3459}
3460
Chaoren Lin97ccc292015-02-03 01:51:12 +00003461Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003462NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003463 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003464{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003465 ReadRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003466 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003467 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003468}
3469
Chaoren Lin97ccc292015-02-03 01:51:12 +00003470Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003471NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3472 const char* reg_name, const RegisterValue &value)
3473{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003474 WriteRegOperation op(tid, offset, reg_name, value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003475 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003476 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003477}
3478
Chaoren Lin97ccc292015-02-03 01:51:12 +00003479Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003480NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3481{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003482 ReadGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003483 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003484 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003485}
3486
Chaoren Lin97ccc292015-02-03 01:51:12 +00003487Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003488NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3489{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003490 ReadFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003491 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003492 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003493}
3494
Chaoren Lin97ccc292015-02-03 01:51:12 +00003495Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003496NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3497{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003498 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003499 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003500 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003501}
3502
Chaoren Lin97ccc292015-02-03 01:51:12 +00003503Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003504NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3505{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003506 WriteGPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003507 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003508 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003509}
3510
Chaoren Lin97ccc292015-02-03 01:51:12 +00003511Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003512NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3513{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003514 WriteFPROperation op(tid, buf, buf_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003515 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003516 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003517}
3518
Chaoren Lin97ccc292015-02-03 01:51:12 +00003519Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003520NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3521{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003522 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Todd Fialaaf245d12014-06-30 21:05:18 +00003523 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003524 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003525}
3526
Chaoren Lin97ccc292015-02-03 01:51:12 +00003527Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003528NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3529{
Todd Fialaaf245d12014-06-30 21:05:18 +00003530 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3531
3532 if (log)
3533 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3534 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003535 ResumeOperation op (tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003536 DoOperation (&op);
3537 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003538 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3539 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003540}
3541
Chaoren Lin97ccc292015-02-03 01:51:12 +00003542Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003543NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3544{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003545 SingleStepOperation op(tid, signo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003546 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003547 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003548}
3549
Chaoren Lin97ccc292015-02-03 01:51:12 +00003550Error
3551NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003552{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003553 SiginfoOperation op(tid, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00003554 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003555 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003556}
3557
Chaoren Lin97ccc292015-02-03 01:51:12 +00003558Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003559NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3560{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003561 EventMessageOperation op(tid, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00003562 DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003563 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003564}
3565
3566lldb_private::Error
3567NativeProcessLinux::Detach(lldb::tid_t tid)
3568{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003569 if (tid == LLDB_INVALID_THREAD_ID)
3570 return Error();
3571
3572 DetachOperation op(tid);
3573 DoOperation(&op);
3574 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003575}
3576
3577bool
3578NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3579{
3580 int target_fd = open(path, flags, 0666);
3581
3582 if (target_fd == -1)
3583 return false;
3584
Pavel Labath493c3a12015-02-04 10:36:57 +00003585 if (dup2(target_fd, fd) == -1)
3586 return false;
3587
3588 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003589}
3590
3591void
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003592NativeProcessLinux::StopMonitorThread()
Todd Fialaaf245d12014-06-30 21:05:18 +00003593{
Zachary Turneracee96a2014-09-23 18:32:09 +00003594 if (m_monitor_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003595 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003596 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00003597 m_monitor_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003598 }
3599}
3600
3601void
3602NativeProcessLinux::StopMonitor()
3603{
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00003604 StopMonitorThread();
Chaoren Linfa03ad22015-02-03 01:50:42 +00003605 StopCoordinatorThread ();
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003606 StopOpThread();
Todd Fialaaf245d12014-06-30 21:05:18 +00003607 sem_destroy(&m_operation_pending);
3608 sem_destroy(&m_operation_done);
3609
3610 // TODO: validate whether this still holds, fix up comment.
3611 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3612 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3613 // the descriptor to a ConnectionFileDescriptor object. Consequently
3614 // even though still has the file descriptor, we shouldn't close it here.
3615}
3616
3617void
3618NativeProcessLinux::StopOpThread()
3619{
Zachary Turneracee96a2014-09-23 18:32:09 +00003620 if (!m_operation_thread.IsJoinable())
Todd Fialaaf245d12014-06-30 21:05:18 +00003621 return;
3622
Tamas Berghammer43f2d972015-03-04 11:10:03 +00003623 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00003624 m_operation_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00003625}
3626
Chaoren Linfa03ad22015-02-03 01:50:42 +00003627Error
3628NativeProcessLinux::StartCoordinatorThread ()
3629{
3630 Error error;
3631 static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
3632 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3633
3634 // Skip if thread is already running
3635 if (m_coordinator_thread.IsJoinable())
3636 {
3637 error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
3638 if (log)
3639 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
3640 return error;
3641 }
3642
3643 // Enable verbose logging if lldb thread logging is enabled.
3644 m_coordinator_up->LogEnableEventProcessing (log != nullptr);
3645
3646 if (log)
3647 log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
3648 m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
3649 return error;
3650}
3651
3652void *
3653NativeProcessLinux::CoordinatorThread (void *arg)
3654{
3655 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3656
3657 NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
3658 assert (process && "null process passed to CoordinatorThread");
3659 if (!process)
3660 {
3661 if (log)
3662 log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
3663 return nullptr;
3664 }
3665
3666 // Run the thread state coordinator loop until it is done. This call uses
3667 // efficient waiting for an event to be ready.
3668 while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
3669 {
3670 }
3671
3672 if (log)
3673 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
3674
3675 return nullptr;
3676}
3677
3678void
3679NativeProcessLinux::StopCoordinatorThread()
3680{
3681 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3682 if (log)
3683 log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
3684
3685 // Tell the coordinator we're done. This will cause the coordinator
3686 // run loop thread to exit when the processing queue hits this message.
3687 m_coordinator_up->StopCoordinator ();
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00003688 m_coordinator_thread.Join (nullptr);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003689}
3690
Todd Fialaaf245d12014-06-30 21:05:18 +00003691bool
3692NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3693{
3694 for (auto thread_sp : m_threads)
3695 {
3696 assert (thread_sp && "thread list should not contain NULL threads");
3697 if (thread_sp->GetID () == thread_id)
3698 {
3699 // We have this thread.
3700 return true;
3701 }
3702 }
3703
3704 // We don't have this thread.
3705 return false;
3706}
3707
3708NativeThreadProtocolSP
3709NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3710{
3711 // CONSIDER organize threads by map - we can do better than linear.
3712 for (auto thread_sp : m_threads)
3713 {
3714 if (thread_sp->GetID () == thread_id)
3715 return thread_sp;
3716 }
3717
3718 // We don't have this thread.
3719 return NativeThreadProtocolSP ();
3720}
3721
3722bool
3723NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3724{
3725 Mutex::Locker locker (m_threads_mutex);
3726 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3727 {
3728 if (*it && ((*it)->GetID () == thread_id))
3729 {
3730 m_threads.erase (it);
3731 return true;
3732 }
3733 }
3734
3735 // Didn't find it.
3736 return false;
3737}
3738
3739NativeThreadProtocolSP
3740NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3741{
3742 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3743
3744 Mutex::Locker locker (m_threads_mutex);
3745
3746 if (log)
3747 {
3748 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3749 __FUNCTION__,
3750 GetID (),
3751 thread_id);
3752 }
3753
3754 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3755
3756 // If this is the first thread, save it as the current thread
3757 if (m_threads.empty ())
3758 SetCurrentThreadID (thread_id);
3759
3760 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3761 m_threads.push_back (thread_sp);
3762
3763 return thread_sp;
3764}
3765
3766NativeThreadProtocolSP
3767NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3768{
3769 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3770
3771 Mutex::Locker locker (m_threads_mutex);
3772 if (log)
3773 {
3774 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3775 __FUNCTION__,
3776 GetID (),
3777 thread_id);
3778 }
3779
3780 // Retrieve the thread if it is already getting tracked.
3781 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3782 if (thread_sp)
3783 {
3784 if (log)
3785 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3786 __FUNCTION__,
3787 GetID (),
3788 thread_id);
3789 created = false;
3790 return thread_sp;
3791
3792 }
3793
3794 // Create the thread metadata since it isn't being tracked.
3795 if (log)
3796 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3797 __FUNCTION__,
3798 GetID (),
3799 thread_id);
3800
3801 thread_sp.reset (new NativeThreadLinux (this, thread_id));
3802 m_threads.push_back (thread_sp);
3803 created = true;
3804
3805 return thread_sp;
3806}
3807
3808Error
3809NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3810{
Todd Fiala75f47c32014-10-11 21:42:09 +00003811 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003812
3813 Error error;
3814
3815 // Get a linux thread pointer.
3816 if (!thread_sp)
3817 {
3818 error.SetErrorString ("null thread_sp");
3819 if (log)
3820 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3821 return error;
3822 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003823 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003824
3825 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003826 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003827 if (!context_sp)
3828 {
3829 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3830 if (log)
3831 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3832 return error;
3833 }
3834
3835 uint32_t breakpoint_size = 0;
3836 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3837 if (error.Fail ())
3838 {
3839 if (log)
3840 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3841 return error;
3842 }
3843 else
3844 {
3845 if (log)
3846 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3847 }
3848
3849 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3850 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3851 lldb::addr_t breakpoint_addr = initial_pc_addr;
3852 if (breakpoint_size > static_cast<lldb::addr_t> (0))
3853 {
3854 // Do not allow breakpoint probe to wrap around.
3855 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3856 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3857 }
3858
3859 // Check if we stopped because of a breakpoint.
3860 NativeBreakpointSP breakpoint_sp;
3861 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3862 if (!error.Success () || !breakpoint_sp)
3863 {
3864 // We didn't find one at a software probe location. Nothing to do.
3865 if (log)
3866 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3867 return Error ();
3868 }
3869
3870 // If the breakpoint is not a software breakpoint, nothing to do.
3871 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3872 {
3873 if (log)
3874 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3875 return Error ();
3876 }
3877
3878 //
3879 // We have a software breakpoint and need to adjust the PC.
3880 //
3881
3882 // Sanity check.
3883 if (breakpoint_size == 0)
3884 {
3885 // Nothing to do! How did we get here?
3886 if (log)
3887 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);
3888 return Error ();
3889 }
3890
3891 // Change the program counter.
3892 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003893 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 +00003894
3895 error = context_sp->SetPC (breakpoint_addr);
3896 if (error.Fail ())
3897 {
3898 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003899 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 +00003900 return error;
3901 }
3902
3903 return error;
3904}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003905
3906void
3907NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
3908{
3909 const bool is_stopped = true;
3910 m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
3911}
3912
3913void
3914NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
3915{
3916 m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
3917}
3918
3919void
3920NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
3921{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003922 m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003923}
3924
3925void
3926NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
3927 const std::function<void (lldb::tid_t tid)> &call_after_function)
3928{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003929 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3930 if (log)
3931 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
3932
Chaoren Linfa03ad22015-02-03 01:50:42 +00003933 const lldb::pid_t pid = GetID ();
Chaoren Lin938fcf62015-02-03 01:50:44 +00003934 m_coordinator_up->CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003935 [=](lldb::tid_t request_stop_tid)
3936 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003937 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003938 },
3939 call_after_function,
3940 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003941}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003942
Chaoren Lin03f12d62015-02-03 01:50:49 +00003943void
3944NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
3945 lldb::tid_t skip_stop_request_tid,
3946 const std::function<void (lldb::tid_t tid)> &call_after_function)
3947{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003948 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3949 if (log)
3950 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
3951
Chaoren Lin03f12d62015-02-03 01:50:49 +00003952 const lldb::pid_t pid = GetID ();
3953 m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
3954 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
3955 [=](lldb::tid_t request_stop_tid)
3956 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00003957 return RequestThreadStop(pid, request_stop_tid);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003958 },
3959 call_after_function,
3960 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00003961}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003962
3963lldb_private::Error
3964NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
3965{
3966 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3967 if (log)
3968 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
3969
3970 Error err;
3971 errno = 0;
3972 if (::tgkill (pid, tid, SIGSTOP) != 0)
3973 {
3974 err.SetErrorToErrno ();
3975 if (log)
3976 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
3977 }
3978
3979 return err;
3980}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003981
3982Error
3983NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3984{
3985 char maps_file_name[32];
3986 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3987
3988 FileSpec maps_file_spec(maps_file_name, false);
3989 if (!maps_file_spec.Exists()) {
3990 file_spec.Clear();
3991 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3992 }
3993
3994 FileSpec module_file_spec(module_path, true);
3995
3996 std::ifstream maps_file(maps_file_name);
3997 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3998 StringRef maps_data(maps_data_str.c_str());
3999
4000 while (!maps_data.empty())
4001 {
4002 StringRef maps_row;
4003 std::tie(maps_row, maps_data) = maps_data.split('\n');
4004
4005 SmallVector<StringRef, 16> maps_columns;
4006 maps_row.split(maps_columns, StringRef(" "), -1, false);
4007
4008 if (maps_columns.size() >= 6)
4009 {
4010 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4011 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4012 return Error();
4013 }
4014 }
4015
4016 file_spec.Clear();
4017 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4018 module_file_spec.GetFilename().AsCString(), GetID());
4019}