blob: 323c55b3c54693058b6d44a064a56ecb7bbe12cd [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>
Pavel Labathc0765592015-05-06 10:46:34 +000023#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000024#include <string>
25
26// Other libraries and framework includes
27#include "lldb/Core/Debugger.h"
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000028#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/Error.h"
30#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000031#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000032#include "lldb/Core/RegisterValue.h"
33#include "lldb/Core/Scalar.h"
34#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000035#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000036#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000037#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000038#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000039#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000042#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000044#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "lldb/Utility/PseudoTerminal.h"
46
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000048#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000049#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
51#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054// System includes - They have to be included after framework includes because they define some
55// macros which collide with variable names in other modules
56#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/personality.h>
58#include <sys/ptrace.h>
59#include <sys/socket.h>
Pavel Labath1107b5a2015-04-17 14:07:49 +000060#include <sys/signalfd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000061#include <sys/syscall.h>
62#include <sys/types.h>
63#include <sys/uio.h>
64#include <sys/user.h>
65#include <sys/wait.h>
66
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000067#if defined (__arm64__) || defined (__aarch64__)
68// NT_PRSTATUS and NT_FPREGSET definition
69#include <elf.h>
70#endif
71
Todd Fialacacde7d2014-09-27 16:54:22 +000072#ifdef __ANDROID__
73#define __ptrace_request int
74#define PT_DETACH PTRACE_DETACH
75#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000076
77#define DEBUG_PTRACE_MAXBYTES 20
78
79// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000080#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000081#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000082 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000083#endif
Todd Fialadda61942014-07-02 21:34:04 +000084#endif
85#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000086#ifndef PTRACE_SETREGS
87 #define PTRACE_SETREGS 13
88#endif
Todd Fialadda61942014-07-02 21:34:04 +000089#endif
90#ifndef PT_GETFPREGS
91#ifndef PTRACE_GETFPREGS
92 #define PTRACE_GETFPREGS 14
93#endif
94#endif
95#ifndef PT_SETFPREGS
96#ifndef PTRACE_SETFPREGS
97 #define PTRACE_SETFPREGS 15
98#endif
99#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000100#ifndef PTRACE_GETREGSET
101 #define PTRACE_GETREGSET 0x4204
102#endif
103#ifndef PTRACE_SETREGSET
104 #define PTRACE_SETREGSET 0x4205
105#endif
106#ifndef PTRACE_GET_THREAD_AREA
107 #define PTRACE_GET_THREAD_AREA 25
108#endif
109#ifndef PTRACE_ARCH_PRCTL
110 #define PTRACE_ARCH_PRCTL 30
111#endif
112#ifndef ARCH_GET_FS
113 #define ARCH_SET_GS 0x1001
114 #define ARCH_SET_FS 0x1002
115 #define ARCH_GET_FS 0x1003
116 #define ARCH_GET_GS 0x1004
117#endif
118
Todd Fiala0bce1b62014-08-17 00:10:50 +0000119#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121// Support hardware breakpoints in case it has not been defined
122#ifndef TRAP_HWBKPT
123 #define TRAP_HWBKPT 4
124#endif
125
126// Try to define a macro to encapsulate the tgkill syscall
127// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000128#define tgkill(pid, tid, sig) \
129 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000130
131// We disable the tracing of ptrace calls for integration builds to
132// avoid the additional indirection and checks.
133#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000134#define PTRACE(req, pid, addr, data, data_size, error) \
135 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000136#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000137#define PTRACE(req, pid, addr, data, data_size, error) \
138 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000139#endif
140
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000141using namespace lldb;
142using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000143using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000144using namespace llvm;
145
Todd Fialaaf245d12014-06-30 21:05:18 +0000146// Private bits we only need internally.
147namespace
148{
Todd Fialaaf245d12014-06-30 21:05:18 +0000149 const UnixSignals&
150 GetUnixSignals ()
151 {
152 static process_linux::LinuxSignals signals;
153 return signals;
154 }
155
Todd Fialaaf245d12014-06-30 21:05:18 +0000156 Error
157 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
158 {
159 // Grab process info for the running process.
160 ProcessInstanceInfo process_info;
161 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000162 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000163
164 // Resolve the executable module.
165 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000166 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000167 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
168 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000169 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000170 exe_module_sp,
171 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
172
173 if (!error.Success ())
174 return error;
175
176 // Check if we've got our architecture from the exe_module.
177 arch = exe_module_sp->GetArchitecture ();
178 if (arch.IsValid ())
179 return Error();
180 else
181 return Error("failed to retrieve a valid architecture from the exe module");
182 }
183
184 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000185 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000186 {
187 uint8_t *ptr = (uint8_t *)bytes;
188 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
189 for(uint32_t i=0; i<loop_count; i++)
190 {
191 s.Printf ("[%x]", *ptr);
192 ptr++;
193 }
194 }
195
196 void
197 PtraceDisplayBytes(int &req, void *data, size_t data_size)
198 {
199 StreamString buf;
200 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
201 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
202
203 if (verbose_log)
204 {
205 switch(req)
206 {
207 case PTRACE_POKETEXT:
208 {
209 DisplayBytes(buf, &data, 8);
210 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
211 break;
212 }
213 case PTRACE_POKEDATA:
214 {
215 DisplayBytes(buf, &data, 8);
216 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
217 break;
218 }
219 case PTRACE_POKEUSER:
220 {
221 DisplayBytes(buf, &data, 8);
222 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
223 break;
224 }
225 case PTRACE_SETREGS:
226 {
227 DisplayBytes(buf, data, data_size);
228 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
229 break;
230 }
231 case PTRACE_SETFPREGS:
232 {
233 DisplayBytes(buf, data, data_size);
234 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
235 break;
236 }
237 case PTRACE_SETSIGINFO:
238 {
239 DisplayBytes(buf, data, sizeof(siginfo_t));
240 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
241 break;
242 }
243 case PTRACE_SETREGSET:
244 {
245 // Extract iov_base from data, which is a pointer to the struct IOVEC
246 DisplayBytes(buf, *(void **)data, data_size);
247 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
248 break;
249 }
250 default:
251 {
252 }
253 }
254 }
255 }
256
257 // Wrapper for ptrace to catch errors and log calls.
258 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
259 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000260 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
261 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000262 {
263 long int result;
264
265 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
266
267 PtraceDisplayBytes(req, data, data_size);
268
Chaoren Lin97ccc292015-02-03 01:51:12 +0000269 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000270 errno = 0;
271 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000272 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000273 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000274 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000275
Chaoren Lin97ccc292015-02-03 01:51:12 +0000276 if (result == -1)
277 error.SetErrorToErrno();
278
Todd Fialaaf245d12014-06-30 21:05:18 +0000279 if (log)
280 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
281 reqName, pid, addr, data, data_size, result, file, line);
282
283 PtraceDisplayBytes(req, data, data_size);
284
Chaoren Lin97ccc292015-02-03 01:51:12 +0000285 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000286 {
287 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000288 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000289 {
290 case ESRCH: str = "ESRCH"; break;
291 case EINVAL: str = "EINVAL"; break;
292 case EBUSY: str = "EBUSY"; break;
293 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000294 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000295 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000296 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000297 }
298
299 return result;
300 }
301
302#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
303 // Wrapper for ptrace when logging is not required.
304 // Sets errno to 0 prior to calling ptrace.
305 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000306 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000307 {
308 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000309
310 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000311 errno = 0;
312 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000313 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000314 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000315 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000316
317 if (result == -1)
318 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000319 return result;
320 }
321#endif
322
323 //------------------------------------------------------------------------------
324 // Static implementations of NativeProcessLinux::ReadMemory and
325 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
326 // functions without needed to go thru the thread funnel.
327
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000328 size_t
329 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000330 lldb::pid_t pid,
331 lldb::addr_t vm_addr,
332 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000333 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 Error &error)
335 {
336 // ptrace word size is determined by the host, not the child
337 static const unsigned word_size = sizeof(void*);
338 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000339 size_t bytes_read;
340 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000341 long data;
342
343 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
344 if (log)
345 ProcessPOSIXLog::IncNestLevel();
346 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
347 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
348 pid, word_size, (void*)vm_addr, buf, size);
349
350 assert(sizeof(data) >= word_size);
351 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
352 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000353 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
354 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000355 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000356 if (log)
357 ProcessPOSIXLog::DecNestLevel();
358 return bytes_read;
359 }
360
361 remainder = size - bytes_read;
362 remainder = remainder > word_size ? word_size : remainder;
363
364 // Copy the data into our buffer
365 for (unsigned i = 0; i < remainder; ++i)
366 dst[i] = ((data >> i*8) & 0xFF);
367
368 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
369 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
370 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
371 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
372 {
373 uintptr_t print_dst = 0;
374 // Format bytes from data by moving into print_dst for log output
375 for (unsigned i = 0; i < remainder; ++i)
376 print_dst |= (((data >> i*8) & 0xFF) << i*8);
377 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
378 (void*)vm_addr, print_dst, (unsigned long)data);
379 }
380
381 vm_addr += word_size;
382 dst += word_size;
383 }
384
385 if (log)
386 ProcessPOSIXLog::DecNestLevel();
387 return bytes_read;
388 }
389
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000390 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000391 DoWriteMemory(
392 lldb::pid_t pid,
393 lldb::addr_t vm_addr,
394 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000395 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000396 Error &error)
397 {
398 // ptrace word size is determined by the host, not the child
399 static const unsigned word_size = sizeof(void*);
400 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000401 size_t bytes_written = 0;
402 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000403
404 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
405 if (log)
406 ProcessPOSIXLog::IncNestLevel();
407 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
408 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
409 pid, word_size, (void*)vm_addr, buf, size);
410
411 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
412 {
413 remainder = size - bytes_written;
414 remainder = remainder > word_size ? word_size : remainder;
415
416 if (remainder == word_size)
417 {
418 unsigned long data = 0;
419 assert(sizeof(data) >= word_size);
420 for (unsigned i = 0; i < word_size; ++i)
421 data |= (unsigned long)src[i] << i*8;
422
423 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
424 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
425 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
426 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
427 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000428 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000429
Chaoren Lin97ccc292015-02-03 01:51:12 +0000430 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000431 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000432 if (log)
433 ProcessPOSIXLog::DecNestLevel();
434 return bytes_written;
435 }
436 }
437 else
438 {
439 unsigned char buff[8];
440 if (DoReadMemory(pid, vm_addr,
441 buff, word_size, error) != word_size)
442 {
443 if (log)
444 ProcessPOSIXLog::DecNestLevel();
445 return bytes_written;
446 }
447
448 memcpy(buff, src, remainder);
449
450 if (DoWriteMemory(pid, vm_addr,
451 buff, word_size, error) != word_size)
452 {
453 if (log)
454 ProcessPOSIXLog::DecNestLevel();
455 return bytes_written;
456 }
457
458 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
459 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
460 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
461 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
462 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000463 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000464 }
465
466 vm_addr += word_size;
467 src += word_size;
468 }
469 if (log)
470 ProcessPOSIXLog::DecNestLevel();
471 return bytes_written;
472 }
473
474 //------------------------------------------------------------------------------
475 /// @class Operation
476 /// @brief Represents a NativeProcessLinux operation.
477 ///
478 /// Under Linux, it is not possible to ptrace() from any other thread but the
479 /// one that spawned or attached to the process from the start. Therefore, when
480 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
481 /// process the operation must be "funneled" to a specific thread to perform the
482 /// task. The Operation class provides an abstract base for all services the
483 /// NativeProcessLinux must perform via the single virtual function Execute, thus
484 /// encapsulating the code that needs to run in the privileged context.
485 class Operation
486 {
487 public:
488 Operation () : m_error() { }
489
490 virtual
491 ~Operation() {}
492
493 virtual void
494 Execute (NativeProcessLinux *process) = 0;
495
496 const Error &
497 GetError () const { return m_error; }
498
499 protected:
500 Error m_error;
501 };
502
503 //------------------------------------------------------------------------------
504 /// @class ReadOperation
505 /// @brief Implements NativeProcessLinux::ReadMemory.
506 class ReadOperation : public Operation
507 {
508 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000509 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000510 lldb::addr_t addr,
511 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000512 size_t size,
513 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000514 Operation (),
515 m_addr (addr),
516 m_buff (buff),
517 m_size (size),
518 m_result (result)
519 {
520 }
521
522 void Execute (NativeProcessLinux *process) override;
523
524 private:
525 lldb::addr_t m_addr;
526 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000527 size_t m_size;
528 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000529 };
530
531 void
532 ReadOperation::Execute (NativeProcessLinux *process)
533 {
534 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
535 }
536
537 //------------------------------------------------------------------------------
538 /// @class WriteOperation
539 /// @brief Implements NativeProcessLinux::WriteMemory.
540 class WriteOperation : public Operation
541 {
542 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000543 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000544 lldb::addr_t addr,
545 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000546 size_t size,
547 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000548 Operation (),
549 m_addr (addr),
550 m_buff (buff),
551 m_size (size),
552 m_result (result)
553 {
554 }
555
556 void Execute (NativeProcessLinux *process) override;
557
558 private:
559 lldb::addr_t m_addr;
560 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000561 size_t m_size;
562 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000563 };
564
565 void
566 WriteOperation::Execute(NativeProcessLinux *process)
567 {
568 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
569 }
570
571 //------------------------------------------------------------------------------
572 /// @class ReadRegOperation
573 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
574 class ReadRegOperation : public Operation
575 {
576 public:
577 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000578 RegisterValue &value)
579 : m_tid(tid),
580 m_offset(static_cast<uintptr_t> (offset)),
581 m_reg_name(reg_name),
582 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000583 { }
584
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000585 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000586
587 private:
588 lldb::tid_t m_tid;
589 uintptr_t m_offset;
590 const char *m_reg_name;
591 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000592 };
593
594 void
595 ReadRegOperation::Execute(NativeProcessLinux *monitor)
596 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000597#if defined (__arm64__) || defined (__aarch64__)
598 if (m_offset > sizeof(struct user_pt_regs))
599 {
600 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
601 if (offset > sizeof(struct user_fpsimd_state))
602 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000603 m_error.SetErrorString("invalid offset value");
604 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000605 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000606 elf_fpregset_t regs;
607 int regset = NT_FPREGSET;
608 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000609
Chaoren Lin97ccc292015-02-03 01:51:12 +0000610 ioVec.iov_base = &regs;
611 ioVec.iov_len = sizeof regs;
612 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
613 if (m_error.Success())
614 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000615 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000616 if (monitor->GetArchitecture(arch))
617 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000618 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000619 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000620 }
621 }
622 else
623 {
624 elf_gregset_t regs;
625 int regset = NT_PRSTATUS;
626 struct iovec ioVec;
627
628 ioVec.iov_base = &regs;
629 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
631 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000632 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000633 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000634 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000635 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000636 else
637 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000638 }
639 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000640#elif defined (__mips__)
641 elf_gregset_t regs;
642 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
643 if (m_error.Success())
644 {
645 lldb_private::ArchSpec arch;
646 if (monitor->GetArchitecture(arch))
647 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
648 else
649 m_error.SetErrorString("failed to get architecture");
650 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000651#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000652 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
653
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000654 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 +0000655 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000656 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000657
Todd Fialaaf245d12014-06-30 21:05:18 +0000658 if (log)
659 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
660 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000661#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000662 }
663
664 //------------------------------------------------------------------------------
665 /// @class WriteRegOperation
666 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
667 class WriteRegOperation : public Operation
668 {
669 public:
670 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000671 const RegisterValue &value)
672 : m_tid(tid),
673 m_offset(offset),
674 m_reg_name(reg_name),
675 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 { }
677
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000678 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000679
680 private:
681 lldb::tid_t m_tid;
682 uintptr_t m_offset;
683 const char *m_reg_name;
684 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 };
686
687 void
688 WriteRegOperation::Execute(NativeProcessLinux *monitor)
689 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000690#if defined (__arm64__) || defined (__aarch64__)
691 if (m_offset > sizeof(struct user_pt_regs))
692 {
693 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
694 if (offset > sizeof(struct user_fpsimd_state))
695 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000696 m_error.SetErrorString("invalid offset value");
697 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000698 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000699 elf_fpregset_t regs;
700 int regset = NT_FPREGSET;
701 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000702
Chaoren Lin97ccc292015-02-03 01:51:12 +0000703 ioVec.iov_base = &regs;
704 ioVec.iov_len = sizeof regs;
705 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000706 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000707 {
708 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
709 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000710 }
711 }
712 else
713 {
714 elf_gregset_t regs;
715 int regset = NT_PRSTATUS;
716 struct iovec ioVec;
717
718 ioVec.iov_base = &regs;
719 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000720 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000721 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000722 {
723 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000724 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000725 }
726 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000727#elif defined (__mips__)
728 elf_gregset_t regs;
729 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
730 if (m_error.Success())
731 {
732 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
733 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
734 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000735#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 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001052} // end of anonymous namespace
1053
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001054// Simple helper function to ensure flags are enabled on the given file
1055// descriptor.
1056static Error
1057EnsureFDFlags(int fd, int flags)
1058{
1059 Error error;
1060
1061 int status = fcntl(fd, F_GETFL);
1062 if (status == -1)
1063 {
1064 error.SetErrorToErrno();
1065 return error;
1066 }
1067
1068 if (fcntl(fd, F_SETFL, status | flags) == -1)
1069 {
1070 error.SetErrorToErrno();
1071 return error;
1072 }
1073
1074 return error;
1075}
1076
1077// This class encapsulates the privileged thread which performs all ptrace and wait operations on
1078// the inferior. The thread consists of a main loop which waits for events and processes them
1079// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1080// the inferior process. Upon receiving this signal we do a waitpid to get more information
1081// and dispatch to NativeProcessLinux::MonitorCallback.
1082// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1083// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1084// pipe, and the completion of the operation is signalled over the semaphore.
1085// - thread exit event: this is signaled from the Monitor destructor by closing the write end
1086// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001087class NativeProcessLinux::Monitor
1088{
Pavel Labath1107b5a2015-04-17 14:07:49 +00001089private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001090 // The initial monitor operation (launch or attach). It returns a inferior process id.
1091 std::unique_ptr<InitialOperation> m_initial_operation_up;
1092
1093 ::pid_t m_child_pid = -1;
1094 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001095
1096 enum { READ, WRITE };
1097 int m_pipefd[2] = {-1, -1};
1098 int m_signal_fd = -1;
1099 HostThread m_thread;
1100
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001101 // current operation which must be executed on the priviliged thread
1102 Mutex m_operation_mutex;
1103 Operation *m_operation = nullptr;
1104 sem_t m_operation_sem;
1105 Error m_operation_error;
1106
Pavel Labath45f5cb32015-05-05 15:05:50 +00001107 unsigned m_operation_nesting_level = 0;
1108
1109 static constexpr char operation_command = 'o';
1110 static constexpr char begin_block_command = '{';
1111 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001112
Pavel Labath1107b5a2015-04-17 14:07:49 +00001113 void
1114 HandleSignals();
1115
1116 void
1117 HandleWait();
1118
1119 // Returns true if the thread should exit.
1120 bool
1121 HandleCommands();
1122
1123 void
1124 MainLoop();
1125
1126 static void *
1127 RunMonitor(void *arg);
1128
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001129 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001130 WaitForAck();
1131
1132 void
1133 BeginOperationBlock()
1134 {
1135 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
1136 WaitForAck();
1137 }
1138
1139 void
1140 EndOperationBlock()
1141 {
1142 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
1143 WaitForAck();
1144 }
1145
Pavel Labath1107b5a2015-04-17 14:07:49 +00001146public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001147 Monitor(const InitialOperation &initial_operation,
1148 NativeProcessLinux *native_process)
1149 : m_initial_operation_up(new InitialOperation(initial_operation)),
1150 m_native_process(native_process)
1151 {
1152 sem_init(&m_operation_sem, 0, 0);
1153 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001154
1155 ~Monitor();
1156
1157 Error
1158 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001159
1160 void
Pavel Labath45f5cb32015-05-05 15:05:50 +00001161 Terminate();
1162
1163 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001164 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001165
1166 class ScopedOperationLock {
1167 Monitor &m_monitor;
1168
1169 public:
1170 ScopedOperationLock(Monitor &monitor)
1171 : m_monitor(monitor)
1172 { m_monitor.BeginOperationBlock(); }
1173
1174 ~ScopedOperationLock()
1175 { m_monitor.EndOperationBlock(); }
1176 };
Pavel Labath1107b5a2015-04-17 14:07:49 +00001177};
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001178constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +00001179constexpr char NativeProcessLinux::Monitor::begin_block_command;
1180constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001181
1182Error
1183NativeProcessLinux::Monitor::Initialize()
1184{
1185 Error error;
1186
1187 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1188 // listening for these signals over a signalfd file descriptors. This allows us to wait for
1189 // multiple kinds of events with select.
1190 sigset_t signals;
1191 sigemptyset(&signals);
1192 sigaddset(&signals, SIGCHLD);
1193 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1194 if (m_signal_fd < 0)
1195 {
1196 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1197 __FUNCTION__, strerror(errno));
1198
1199 }
1200
1201 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1202 {
1203 error.SetErrorToErrno();
1204 return error;
1205 }
1206
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001207 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1208 return error;
1209 }
1210
1211 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1212 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001213 if (!m_thread.IsJoinable())
1214 return Error("Failed to create monitor thread for NativeProcessLinux.");
1215
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001216 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001217 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001218}
1219
1220void
1221NativeProcessLinux::Monitor::DoOperation(Operation *op)
1222{
1223 if (m_thread.EqualsThread(pthread_self())) {
1224 // If we're on the Monitor thread, we can simply execute the operation.
1225 op->Execute(m_native_process);
1226 return;
1227 }
1228
1229 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1230 Mutex::Locker lock(m_operation_mutex);
1231
1232 m_operation = op;
1233
1234 // notify the thread that an operation is ready to be processed
1235 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1236
Pavel Labath45f5cb32015-05-05 15:05:50 +00001237 WaitForAck();
1238}
1239
1240void
1241NativeProcessLinux::Monitor::Terminate()
1242{
1243 if (m_pipefd[WRITE] >= 0)
1244 {
1245 close(m_pipefd[WRITE]);
1246 m_pipefd[WRITE] = -1;
1247 }
1248 if (m_thread.IsJoinable())
1249 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00001250}
1251
Pavel Labath1107b5a2015-04-17 14:07:49 +00001252NativeProcessLinux::Monitor::~Monitor()
1253{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001254 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +00001255 if (m_pipefd[READ] >= 0)
1256 close(m_pipefd[READ]);
1257 if (m_signal_fd >= 0)
1258 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001259 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001260}
1261
1262void
1263NativeProcessLinux::Monitor::HandleSignals()
1264{
1265 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1266
1267 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1268 // all the information from waitpid(). We just need to read all the signals so that we can
1269 // sleep next time we reach select().
1270 while (true)
1271 {
1272 signalfd_siginfo info;
1273 ssize_t size = read(m_signal_fd, &info, sizeof info);
1274 if (size == -1)
1275 {
1276 if (errno == EAGAIN || errno == EWOULDBLOCK)
1277 break; // We are done.
1278 if (errno == EINTR)
1279 continue;
1280 if (log)
1281 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1282 __FUNCTION__, strerror(errno));
1283 break;
1284 }
1285 if (size != sizeof info)
1286 {
1287 // We got incomplete information structure. This should not happen, let's just log
1288 // that.
1289 if (log)
1290 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1291 "structure size is %zd, read returned %zd bytes",
1292 __FUNCTION__, sizeof info, size);
1293 break;
1294 }
1295 if (log)
1296 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1297 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1298 }
1299}
1300
1301void
1302NativeProcessLinux::Monitor::HandleWait()
1303{
1304 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1305 // Process all pending waitpid notifications.
1306 while (true)
1307 {
1308 int status = -1;
1309 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1310
1311 if (wait_pid == 0)
1312 break; // We are done.
1313
1314 if (wait_pid == -1)
1315 {
1316 if (errno == EINTR)
1317 continue;
1318
1319 if (log)
1320 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1321 __FUNCTION__, m_child_pid, strerror(errno));
1322 break;
1323 }
1324
1325 bool exited = false;
1326 int signal = 0;
1327 int exit_status = 0;
1328 const char *status_cstr = NULL;
1329 if (WIFSTOPPED(status))
1330 {
1331 signal = WSTOPSIG(status);
1332 status_cstr = "STOPPED";
1333 }
1334 else if (WIFEXITED(status))
1335 {
1336 exit_status = WEXITSTATUS(status);
1337 status_cstr = "EXITED";
1338 exited = true;
1339 }
1340 else if (WIFSIGNALED(status))
1341 {
1342 signal = WTERMSIG(status);
1343 status_cstr = "SIGNALED";
1344 if (wait_pid == abs(m_child_pid)) {
1345 exited = true;
1346 exit_status = -1;
1347 }
1348 }
1349 else
1350 status_cstr = "(\?\?\?)";
1351
1352 if (log)
1353 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1354 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1355 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1356
1357 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1358 }
1359}
1360
1361bool
1362NativeProcessLinux::Monitor::HandleCommands()
1363{
1364 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1365
1366 while (true)
1367 {
1368 char command = 0;
1369 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1370 if (size == -1)
1371 {
1372 if (errno == EAGAIN || errno == EWOULDBLOCK)
1373 return false;
1374 if (errno == EINTR)
1375 continue;
1376 if (log)
1377 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1378 return true;
1379 }
1380 if (size == 0) // end of file - write end closed
1381 {
1382 if (log)
1383 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001384 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +00001385 return true; // We are done.
1386 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001387
1388 switch (command)
1389 {
1390 case operation_command:
1391 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001392 break;
1393 case begin_block_command:
1394 ++m_operation_nesting_level;
1395 break;
1396 case end_block_command:
1397 assert(m_operation_nesting_level > 0);
1398 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001399 break;
1400 default:
1401 if (log)
1402 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1403 __FUNCTION__, command);
1404 }
Pavel Labath45f5cb32015-05-05 15:05:50 +00001405
1406 // notify calling thread that the command has been processed
1407 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001408 }
1409}
1410
1411void
1412NativeProcessLinux::Monitor::MainLoop()
1413{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001414 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1415 m_initial_operation_up.reset();
1416 m_child_pid = -getpgid(child_pid),
1417 sem_post(&m_operation_sem);
1418
Pavel Labath1107b5a2015-04-17 14:07:49 +00001419 while (true)
1420 {
1421 fd_set fds;
1422 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001423 // Only process waitpid events if we are outside of an operation block. Any pending
1424 // events will be processed after we leave the block.
1425 if (m_operation_nesting_level == 0)
1426 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001427 FD_SET(m_pipefd[READ], &fds);
1428
1429 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1430 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1431 if (r < 0)
1432 {
1433 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1434 if (log)
1435 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1436 __FUNCTION__, strerror(errno));
1437 return;
1438 }
1439
1440 if (FD_ISSET(m_pipefd[READ], &fds))
1441 {
1442 if (HandleCommands())
1443 return;
1444 }
1445
1446 if (FD_ISSET(m_signal_fd, &fds))
1447 {
1448 HandleSignals();
1449 HandleWait();
1450 }
1451 }
1452}
1453
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001454Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001455NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001456{
1457 Error error;
1458 while (sem_wait(&m_operation_sem) != 0)
1459 {
1460 if (errno == EINTR)
1461 continue;
1462
1463 error.SetErrorToErrno();
1464 return error;
1465 }
1466
1467 return m_operation_error;
1468}
1469
Pavel Labath1107b5a2015-04-17 14:07:49 +00001470void *
1471NativeProcessLinux::Monitor::RunMonitor(void *arg)
1472{
1473 static_cast<Monitor *>(arg)->MainLoop();
1474 return nullptr;
1475}
1476
1477
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001478NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001479 char const **argv,
1480 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001481 const std::string &stdin_path,
1482 const std::string &stdout_path,
1483 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001484 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001485 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001486 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +00001487 m_argv(argv),
1488 m_envp(envp),
1489 m_stdin_path(stdin_path),
1490 m_stdout_path(stdout_path),
1491 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001492 m_working_dir(working_dir),
1493 m_launch_info(launch_info)
1494{
1495}
Todd Fialaaf245d12014-06-30 21:05:18 +00001496
1497NativeProcessLinux::LaunchArgs::~LaunchArgs()
1498{ }
1499
Todd Fialaaf245d12014-06-30 21:05:18 +00001500// -----------------------------------------------------------------------------
1501// Public Static Methods
1502// -----------------------------------------------------------------------------
1503
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001504Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001505NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001506 Module *exe_module,
1507 ProcessLaunchInfo &launch_info,
1508 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001509 NativeProcessProtocolSP &native_process_sp)
1510{
1511 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1512
1513 Error error;
1514
1515 // Verify the working directory is valid if one was specified.
1516 const char* working_dir = launch_info.GetWorkingDirectory ();
1517 if (working_dir)
1518 {
1519 FileSpec working_dir_fs (working_dir, true);
1520 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1521 {
1522 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1523 return error;
1524 }
1525 }
1526
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001527 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001528
1529 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001530 std::string stdin_path;
1531 std::string stdout_path;
1532 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001533
1534 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001535 if (file_action)
1536 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001537
1538 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001539 if (file_action)
1540 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001541
1542 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001543 if (file_action)
1544 stderr_path = file_action->GetPath ();
1545
1546 if (log)
1547 {
1548 if (!stdin_path.empty ())
1549 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1550 else
1551 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1552
1553 if (!stdout_path.empty ())
1554 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1555 else
1556 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1557
1558 if (!stderr_path.empty ())
1559 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1560 else
1561 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1562 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001563
1564 // Create the NativeProcessLinux in launch mode.
1565 native_process_sp.reset (new NativeProcessLinux ());
1566
1567 if (log)
1568 {
1569 int i = 0;
1570 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1571 {
1572 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1573 ++i;
1574 }
1575 }
1576
1577 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1578 {
1579 native_process_sp.reset ();
1580 error.SetErrorStringWithFormat ("failed to register the native delegate");
1581 return error;
1582 }
1583
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001584 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001585 exe_module,
1586 launch_info.GetArguments ().GetConstArgumentVector (),
1587 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1588 stdin_path,
1589 stdout_path,
1590 stderr_path,
1591 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001592 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001593 error);
1594
1595 if (error.Fail ())
1596 {
1597 native_process_sp.reset ();
1598 if (log)
1599 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1600 return error;
1601 }
1602
1603 launch_info.SetProcessID (native_process_sp->GetID ());
1604
1605 return error;
1606}
1607
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001608Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001609NativeProcessLinux::AttachToProcess (
1610 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001611 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001612 NativeProcessProtocolSP &native_process_sp)
1613{
1614 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1615 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1616 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1617
1618 // Grab the current platform architecture. This should be Linux,
1619 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001620 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001621 if (!platform_sp)
1622 return Error("failed to get a valid default platform");
1623
1624 // Retrieve the architecture for the running process.
1625 ArchSpec process_arch;
1626 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1627 if (!error.Success ())
1628 return error;
1629
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001630 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001631
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001632 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001633 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001634 error.SetErrorStringWithFormat ("failed to register the native delegate");
1635 return error;
1636 }
1637
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001638 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001639 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001640 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001641
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001642 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001643 return error;
1644}
1645
1646// -----------------------------------------------------------------------------
1647// Public Instance Methods
1648// -----------------------------------------------------------------------------
1649
1650NativeProcessLinux::NativeProcessLinux () :
1651 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1652 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001653 m_supports_mem_region (eLazyBoolCalculate),
1654 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001655 m_mem_region_cache_mutex (),
Pavel Labath5eb721e2015-05-07 08:30:31 +00001656 m_tid_map ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001657{
1658}
1659
1660//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001661// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1662// Refer to Monitor and Operation classes to see why this is necessary.
1663//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001664void
1665NativeProcessLinux::LaunchInferior (
1666 Module *module,
1667 const char *argv[],
1668 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001669 const std::string &stdin_path,
1670 const std::string &stdout_path,
1671 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001672 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001673 const ProcessLaunchInfo &launch_info,
1674 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001675{
1676 if (module)
1677 m_arch = module->GetArchitecture ();
1678
Chaoren Linfa03ad22015-02-03 01:50:42 +00001679 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001680
1681 std::unique_ptr<LaunchArgs> args(
1682 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001683 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001684 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001685 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001686
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001687 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001688 if (!error.Success ())
1689 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001690}
1691
1692void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001693NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001694{
1695 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1696 if (log)
1697 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1698
1699 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001700 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001701 if (!platform_sp)
1702 {
1703 if (log)
1704 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1705 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001706 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001707 }
1708
1709 // Gather info about the process.
1710 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001711 if (!platform_sp->GetProcessInfo (pid, process_info))
1712 {
1713 if (log)
1714 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1715 error.SetErrorString ("failed to get process info");
1716 return;
1717 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001718
1719 // Resolve the executable module
1720 ModuleSP exe_module_sp;
1721 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001722 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001723 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001724 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001725 if (!error.Success())
1726 return;
1727
1728 // Set the architecture to the exe architecture.
1729 m_arch = exe_module_sp->GetArchitecture();
1730 if (log)
1731 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1732
1733 m_pid = pid;
1734 SetState(eStateAttaching);
1735
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001736 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 if (!error.Success ())
1738 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001739}
1740
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001741void
1742NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001743{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001744 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001745}
1746
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001747::pid_t
1748NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001749{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001750 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001751
1752 const char **argv = args->m_argv;
1753 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001754 const char *working_dir = args->m_working_dir;
1755
1756 lldb_utility::PseudoTerminal terminal;
1757 const size_t err_len = 1024;
1758 char err_str[err_len];
1759 lldb::pid_t pid;
1760 NativeThreadProtocolSP thread_sp;
1761
1762 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001763
1764 // Propagate the environment if one is not supplied.
1765 if (envp == NULL || envp[0] == NULL)
1766 envp = const_cast<const char **>(environ);
1767
1768 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1769 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001770 error.SetErrorToGenericError();
1771 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1772 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001773 }
1774
1775 // Recognized child exit status codes.
1776 enum {
1777 ePtraceFailed = 1,
1778 eDupStdinFailed,
1779 eDupStdoutFailed,
1780 eDupStderrFailed,
1781 eChdirFailed,
1782 eExecFailed,
1783 eSetGidFailed
1784 };
1785
1786 // Child process.
1787 if (pid == 0)
1788 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001789 // FIXME consider opening a pipe between parent/child and have this forked child
1790 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001791
Todd Fiala75f47c32014-10-11 21:42:09 +00001792 // Start tracing this child that is about to exec.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001793 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1794 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001795 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001796
Pavel Labath493c3a12015-02-04 10:36:57 +00001797 // terminal has already dupped the tty descriptors to stdin/out/err.
1798 // This closes original fd from which they were copied (and avoids
1799 // leaking descriptors to the debugged process.
1800 terminal.CloseSlaveFileDescriptor();
1801
Todd Fialaaf245d12014-06-30 21:05:18 +00001802 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001803 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001804 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001805
1806 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001807 if (setpgid(0, 0) != 0)
1808 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001809 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001810 // Don't allow this to prevent an inferior exec.
1811 }
1812
1813 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001814 if (!args->m_stdin_path.empty ())
1815 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001816 exit(eDupStdinFailed);
1817
Todd Fiala75f47c32014-10-11 21:42:09 +00001818 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001819 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001820 exit(eDupStdoutFailed);
1821
Todd Fiala75f47c32014-10-11 21:42:09 +00001822 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001823 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001824 exit(eDupStderrFailed);
1825
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001826 // Close everything besides stdin, stdout, and stderr that has no file
1827 // action to avoid leaking
1828 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1829 if (!args->m_launch_info.GetFileActionForFD(fd))
1830 close(fd);
1831
Todd Fialaaf245d12014-06-30 21:05:18 +00001832 // Change working directory
1833 if (working_dir != NULL && working_dir[0])
1834 if (0 != ::chdir(working_dir))
1835 exit(eChdirFailed);
1836
Todd Fiala0bce1b62014-08-17 00:10:50 +00001837 // Disable ASLR if requested.
1838 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1839 {
1840 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1841 if (old_personality == -1)
1842 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001843 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001844 }
1845 else
1846 {
1847 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1848 if (new_personality == -1)
1849 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001850 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001851 }
1852 else
1853 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001854 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001855 }
1856 }
1857 }
1858
Todd Fiala75f47c32014-10-11 21:42:09 +00001859 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001860 execve(argv[0],
1861 const_cast<char *const *>(argv),
1862 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001863
1864 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001865 exit(eExecFailed);
1866 }
1867
Todd Fiala75f47c32014-10-11 21:42:09 +00001868 //
1869 // This is the parent code here.
1870 //
1871 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1872
Todd Fialaaf245d12014-06-30 21:05:18 +00001873 // Wait for the child process to trap on its call to execve.
1874 ::pid_t wpid;
1875 int status;
1876 if ((wpid = waitpid(pid, &status, 0)) < 0)
1877 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001878 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001879 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001880 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1881 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001882
1883 // Mark the inferior as invalid.
1884 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001885 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001886
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001887 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001888 }
1889 else if (WIFEXITED(status))
1890 {
1891 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001892 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001893 switch (WEXITSTATUS(status))
1894 {
1895 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001896 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001897 break;
1898 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001899 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001900 break;
1901 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001902 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001903 break;
1904 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001905 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001906 break;
1907 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001908 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001909 break;
1910 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001911 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001912 break;
1913 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001914 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001915 break;
1916 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001917 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001918 break;
1919 }
1920
1921 if (log)
1922 {
1923 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1924 __FUNCTION__,
1925 WEXITSTATUS(status));
1926 }
1927
1928 // Mark the inferior as invalid.
1929 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001930 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001931
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001932 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001933 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001934 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001935 "Could not sync with inferior process.");
1936
1937 if (log)
1938 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1939
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001940 error = SetDefaultPtraceOpts(pid);
1941 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001942 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001943 if (log)
1944 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001945 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001946
1947 // Mark the inferior as invalid.
1948 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001949 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001950
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001951 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001952 }
1953
1954 // Release the master terminal descriptor and pass it off to the
1955 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001956 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1957 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001958
1959 // Set the terminal fd to be in non blocking mode (it simplifies the
1960 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1961 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001962 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1963 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001964 {
1965 if (log)
1966 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001967 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001968
1969 // Mark the inferior as invalid.
1970 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001971 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001972
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001973 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001974 }
1975
1976 if (log)
1977 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1978
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001979 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001980 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001981 NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001982 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00001983
1984 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001985 SetCurrentThreadID (thread_sp->GetID ());
1986 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001987
Todd Fialaaf245d12014-06-30 21:05:18 +00001988 if (log)
1989 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001990 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001991 {
1992 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1993 }
1994 else
1995 {
1996 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001997 __FUNCTION__, error.AsCString ());
1998 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001999 }
2000 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002001 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002002}
2003
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002004::pid_t
2005NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00002006{
Todd Fialaaf245d12014-06-30 21:05:18 +00002007 lldb::ThreadSP inferior;
2008 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2009
2010 // Use a map to keep track of the threads which we have attached/need to attach.
2011 Host::TidMap tids_to_attach;
2012 if (pid <= 1)
2013 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002014 error.SetErrorToGenericError();
2015 error.SetErrorString("Attaching to process 1 is not allowed.");
2016 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002017 }
2018
2019 while (Host::FindProcessThreads(pid, tids_to_attach))
2020 {
2021 for (Host::TidMap::iterator it = tids_to_attach.begin();
2022 it != tids_to_attach.end();)
2023 {
2024 if (it->second == false)
2025 {
2026 lldb::tid_t tid = it->first;
2027
2028 // Attach to the requested process.
2029 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002030 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
2031 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002032 {
2033 // No such thread. The thread may have exited.
2034 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002035 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00002036 {
2037 it = tids_to_attach.erase(it);
2038 continue;
2039 }
2040 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002041 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002042 }
2043
2044 int status;
2045 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2046 // At this point we should have a thread stopped if waitpid succeeds.
2047 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2048 {
2049 // No such thread. The thread may have exited.
2050 // More error handling may be needed.
2051 if (errno == ESRCH)
2052 {
2053 it = tids_to_attach.erase(it);
2054 continue;
2055 }
2056 else
2057 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002058 error.SetErrorToErrno();
2059 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002060 }
2061 }
2062
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002063 error = SetDefaultPtraceOpts(tid);
2064 if (error.Fail())
2065 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002066
2067 if (log)
2068 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2069
2070 it->second = true;
2071
2072 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002073 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00002074 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002075
2076 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002077 NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002078 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002079 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002080 }
2081
2082 // move the loop forward
2083 ++it;
2084 }
2085 }
2086
2087 if (tids_to_attach.size() > 0)
2088 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002089 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002090 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002091 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002092 }
2093 else
2094 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002095 error.SetErrorToGenericError();
2096 error.SetErrorString("No such process.");
2097 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002098 }
2099
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002100 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002101}
2102
Chaoren Lin97ccc292015-02-03 01:51:12 +00002103Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002104NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2105{
2106 long ptrace_opts = 0;
2107
2108 // Have the child raise an event on exit. This is used to keep the child in
2109 // limbo until it is destroyed.
2110 ptrace_opts |= PTRACE_O_TRACEEXIT;
2111
2112 // Have the tracer trace threads which spawn in the inferior process.
2113 // TODO: if we want to support tracing the inferiors' child, add the
2114 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2115 ptrace_opts |= PTRACE_O_TRACECLONE;
2116
2117 // Have the tracer notify us before execve returns
2118 // (needed to disable legacy SIGTRAP generation)
2119 ptrace_opts |= PTRACE_O_TRACEEXEC;
2120
Chaoren Lin97ccc292015-02-03 01:51:12 +00002121 Error error;
2122 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2123 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002124}
2125
2126static ExitType convert_pid_status_to_exit_type (int status)
2127{
2128 if (WIFEXITED (status))
2129 return ExitType::eExitTypeExit;
2130 else if (WIFSIGNALED (status))
2131 return ExitType::eExitTypeSignal;
2132 else if (WIFSTOPPED (status))
2133 return ExitType::eExitTypeStop;
2134 else
2135 {
2136 // We don't know what this is.
2137 return ExitType::eExitTypeInvalid;
2138 }
2139}
2140
2141static int convert_pid_status_to_return_code (int status)
2142{
2143 if (WIFEXITED (status))
2144 return WEXITSTATUS (status);
2145 else if (WIFSIGNALED (status))
2146 return WTERMSIG (status);
2147 else if (WIFSTOPPED (status))
2148 return WSTOPSIG (status);
2149 else
2150 {
2151 // We don't know what this is.
2152 return ExitType::eExitTypeInvalid;
2153 }
2154}
2155
Pavel Labath1107b5a2015-04-17 14:07:49 +00002156// Handles all waitpid events from the inferior process.
2157void
2158NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00002159 bool exited,
2160 int signal,
2161 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00002162{
2163 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2164
Todd Fialaaf245d12014-06-30 21:05:18 +00002165 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002166 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002167
2168 // Handle when the thread exits.
2169 if (exited)
2170 {
2171 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002172 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 +00002173
2174 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002175 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002176
Chaoren Linfa03ad22015-02-03 01:50:42 +00002177 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002178 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002179
Todd Fialaaf245d12014-06-30 21:05:18 +00002180 if (is_main_thread)
2181 {
2182 // We only set the exit status and notify the delegate if we haven't already set the process
2183 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2184 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002185 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00002186 if (!already_notified)
2187 {
2188 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002189 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ()));
Todd Fialaaf245d12014-06-30 21:05:18 +00002190 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002191 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002192
2193 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002194 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002195 }
2196 else
2197 {
2198 if (log)
2199 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2200 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002201 }
2202 else
2203 {
2204 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2205 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2206 // and we would have done an all-stop then.
2207 if (log)
2208 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +00002209 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00002210 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00002211 }
2212
2213 // Get details on the signal raised.
2214 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00002215 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00002216 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002217 {
2218 // We have retrieved the signal info. Dispatch appropriately.
2219 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002220 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002221 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00002222 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002223 }
2224 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002225 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002226 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002227 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002228 // This is a group stop reception for this tid.
2229 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002230 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002231 NotifyThreadStop (pid, false);
Todd Fialaaf245d12014-06-30 21:05:18 +00002232 }
2233 else
2234 {
2235 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2236
2237 // A return value of ESRCH means the thread/process is no longer on the system,
2238 // so it was killed somehow outside of our control. Either way, we can't do anything
2239 // with it anymore.
2240
Todd Fialaaf245d12014-06-30 21:05:18 +00002241 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002242 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002243
Chaoren Linfa03ad22015-02-03 01:50:42 +00002244 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002245 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002246
Todd Fialaaf245d12014-06-30 21:05:18 +00002247 if (log)
2248 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002249 __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 +00002250
2251 if (is_main_thread)
2252 {
2253 // Notify the delegate - our process is not available but appears to have been killed outside
2254 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00002255 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2256 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002257 }
2258 else
2259 {
2260 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2261 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002262 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002263 }
2264 }
2265 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002266}
2267
2268void
Pavel Labath426bdf82015-04-28 07:51:52 +00002269NativeProcessLinux::WaitForNewThread(::pid_t tid)
2270{
2271 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2272
2273 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2274
2275 if (new_thread_sp)
2276 {
2277 // We are already tracking the thread - we got the event on the new thread (see
2278 // MonitorSignal) before this one. We are done.
2279 return;
2280 }
2281
2282 // The thread is not tracked yet, let's wait for it to appear.
2283 int status = -1;
2284 ::pid_t wait_pid;
2285 do
2286 {
2287 if (log)
2288 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2289 wait_pid = waitpid(tid, &status, __WALL);
2290 }
2291 while (wait_pid == -1 && errno == EINTR);
2292 // Since we are waiting on a specific tid, this must be the creation event. But let's do
2293 // some checks just in case.
2294 if (wait_pid != tid) {
2295 if (log)
2296 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2297 // The only way I know of this could happen is if the whole process was
2298 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2299 return;
2300 }
2301 if (WIFEXITED(status))
2302 {
2303 if (log)
2304 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2305 // Also a very improbable event.
2306 return;
2307 }
2308
2309 siginfo_t info;
2310 Error error = GetSignalInfo(tid, &info);
2311 if (error.Fail())
2312 {
2313 if (log)
2314 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2315 return;
2316 }
2317
2318 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2319 {
2320 // We should be getting a thread creation signal here, but we received something
2321 // else. There isn't much we can do about it now, so we will just log that. Since the
2322 // thread is alive and we are receiving events from it, we shall pretend that it was
2323 // created properly.
2324 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid);
2325 }
2326
2327 if (log)
2328 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2329 __FUNCTION__, GetID (), tid);
2330
2331 new_thread_sp = AddThread(tid);
2332 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2333 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002334 NotifyThreadCreate (tid, false);
Pavel Labath426bdf82015-04-28 07:51:52 +00002335}
2336
2337void
Todd Fialaaf245d12014-06-30 21:05:18 +00002338NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2339{
2340 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2341 const bool is_main_thread = (pid == GetID ());
2342
2343 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2344 if (!info)
2345 return;
2346
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002347 Mutex::Locker locker (m_threads_mutex);
2348
Todd Fialaaf245d12014-06-30 21:05:18 +00002349 // See if we can find a thread for this signal.
2350 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2351 if (!thread_sp)
2352 {
2353 if (log)
2354 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2355 }
2356
2357 switch (info->si_code)
2358 {
2359 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2360 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2361 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2362
2363 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2364 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002365 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00002366 // creation.
2367 // We don't want to do anything with the parent thread so we just resume it. In case we
2368 // want to implement "break on thread creation" functionality, we would need to stop
2369 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00002370
Pavel Labath426bdf82015-04-28 07:51:52 +00002371 unsigned long event_message = 0;
2372 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002373 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002374 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002375 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
Pavel Labath426bdf82015-04-28 07:51:52 +00002376 } else
2377 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002378
Pavel Labath5fd24c62015-04-23 09:04:35 +00002379 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002380 break;
2381 }
2382
2383 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002384 {
2385 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002386 if (log)
2387 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002388
Chaoren Linfa03ad22015-02-03 01:50:42 +00002389 // The thread state coordinator needs to reset due to the exec.
Pavel Labathc0765592015-05-06 10:46:34 +00002390 ResetForExec ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002391
2392 // 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 +00002393 if (log)
2394 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2395
2396 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002397 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002398 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2399 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002400 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002401 main_thread_sp = thread_sp;
2402 if (log)
2403 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002404 }
2405 else
2406 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002407 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002408 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002409 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002410 }
2411 }
2412
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002413 m_threads.clear ();
2414
2415 if (main_thread_sp)
2416 {
2417 m_threads.push_back (main_thread_sp);
2418 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002419 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002420 }
2421 else
2422 {
2423 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2424 if (log)
2425 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2426 }
2427
Chaoren Linfa03ad22015-02-03 01:50:42 +00002428 // Tell coordinator about about the "new" (since exec) stopped main thread.
2429 const lldb::tid_t main_thread_tid = GetID ();
2430 NotifyThreadCreateStopped (main_thread_tid);
2431
2432 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2433 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002434 // Let our delegate know we have just exec'd.
2435 NotifyDidExec ();
2436
2437 // If we have a main thread, indicate we are stopped.
2438 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002439
2440 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002441 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002442
Todd Fialaaf245d12014-06-30 21:05:18 +00002443 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002444 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002445
2446 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2447 {
2448 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002449
2450 // This thread is currently stopped. It's not actually dead yet, just about to be.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002451 NotifyThreadStop (pid, false);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002452
Todd Fialaaf245d12014-06-30 21:05:18 +00002453 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002454 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002455 data = -1;
2456
2457 if (log)
2458 {
2459 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2460 __FUNCTION__,
2461 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2462 pid,
2463 is_main_thread ? "is main thread" : "not main thread");
2464 }
2465
Todd Fialaaf245d12014-06-30 21:05:18 +00002466 if (is_main_thread)
2467 {
2468 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002469 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002470
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002471 const int signo = static_cast<int> (data);
Pavel Labathc0765592015-05-06 10:46:34 +00002472 RequestThreadResume (pid,
2473 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2474 {
2475 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2476 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002477 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002478
2479 break;
2480 }
2481
2482 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002483 case TRAP_TRACE: // We receive this on single stepping.
2484 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002485 if (thread_sp)
2486 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002487 // If a watchpoint was hit, report it
2488 uint32_t wp_index;
2489 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2490 if (error.Fail() && log)
2491 log->Printf("NativeProcessLinux::%s() "
2492 "received error while checking for watchpoint hits, "
2493 "pid = %" PRIu64 " error = %s",
2494 __FUNCTION__, pid, error.AsCString());
2495 if (wp_index != LLDB_INVALID_INDEX32)
2496 {
2497 MonitorWatchpoint(pid, thread_sp, wp_index);
2498 break;
2499 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002500 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002501 // Otherwise, report step over
2502 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002503 break;
2504
2505 case SI_KERNEL:
2506 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002507 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002508 break;
2509
2510 case SIGTRAP:
2511 case (SIGTRAP | 0x80):
2512 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002513 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2514
2515 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002516 NotifyThreadStop (pid, false);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002517 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002518 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002519
2520
Todd Fialaaf245d12014-06-30 21:05:18 +00002521 // Ignore these signals until we know more about them.
Pavel Labathc0765592015-05-06 10:46:34 +00002522 RequestThreadResume (pid,
2523 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2524 {
2525 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2526 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002527 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002528 break;
2529
2530 default:
2531 assert(false && "Unexpected SIGTRAP code!");
2532 if (log)
2533 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)));
2534 break;
2535
2536 }
2537}
2538
2539void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002540NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2541{
2542 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2543 if (log)
2544 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2545 __FUNCTION__, pid);
2546
2547 if (thread_sp)
2548 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2549
2550 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002551 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002552
2553 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2554 // This would have already happened at the time the Resume() with step operation was signaled.
2555 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2556 // once all running threads have checked in as stopped.
2557 SetCurrentThreadID(pid);
2558 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00002559 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002560}
2561
2562void
2563NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2564{
2565 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2566 if (log)
2567 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2568 __FUNCTION__, pid);
2569
2570 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002571 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002572
2573 // Mark the thread as stopped at breakpoint.
2574 if (thread_sp)
2575 {
2576 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2577 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2578 if (error.Fail())
2579 if (log)
2580 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2581 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002582
2583 auto it = m_threads_stepping_with_breakpoint.find(pid);
2584 if (it != m_threads_stepping_with_breakpoint.end())
2585 {
2586 Error error = RemoveBreakpoint (it->second);
2587 if (error.Fail())
2588 if (log)
2589 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2590 __FUNCTION__, pid, error.AsCString());
2591
2592 m_threads_stepping_with_breakpoint.erase(it);
2593 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2594 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002595 }
2596 else
2597 if (log)
2598 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2599 "warning, cannot process software breakpoint since no thread metadata",
2600 __FUNCTION__, pid);
2601
2602
2603 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002604 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002605}
2606
2607void
2608NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2609{
2610 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2611 if (log)
2612 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2613 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2614 __FUNCTION__, pid, wp_index);
2615
2616 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002617 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002618
2619 // Mark the thread as stopped at watchpoint.
2620 // The address is at (lldb::addr_t)info->si_addr if we need it.
2621 lldbassert(thread_sp && "thread_sp cannot be NULL");
2622 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2623
2624 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002625 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002626}
2627
2628void
Todd Fialaaf245d12014-06-30 21:05:18 +00002629NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2630{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002631 assert (info && "null info");
2632 if (!info)
2633 return;
2634
2635 const int signo = info->si_signo;
2636 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002637
2638 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2639
2640 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2641 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2642 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2643 //
2644 // IOW, user generated signals never generate what we consider to be a
2645 // "crash".
2646 //
2647 // Similarly, ACK signals generated by this monitor.
2648
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002649 Mutex::Locker locker (m_threads_mutex);
2650
Todd Fialaaf245d12014-06-30 21:05:18 +00002651 // See if we can find a thread for this signal.
2652 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2653 if (!thread_sp)
2654 {
2655 if (log)
2656 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2657 }
2658
2659 // Handle the signal.
2660 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2661 {
2662 if (log)
2663 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2664 __FUNCTION__,
2665 GetUnixSignals ().GetSignalAsCString (signo),
2666 signo,
2667 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2668 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002669 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002670 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002671 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002672
Todd Fiala58a2f662014-08-12 17:02:07 +00002673 // Check for new thread notification.
2674 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2675 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002676 // A new thread creation is being signaled. This is one of two parts that come in
2677 // a non-deterministic order. This code handles the case where the new thread event comes
2678 // before the event on the parent thread. For the opposite case see code in
2679 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002680 if (log)
2681 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2682 __FUNCTION__, GetID (), pid);
2683
Pavel Labath5fd24c62015-04-23 09:04:35 +00002684 thread_sp = AddThread(pid);
2685 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2686 // We can now resume the newly created thread.
2687 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2688 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002689 NotifyThreadCreate (pid, false);
Todd Fiala58a2f662014-08-12 17:02:07 +00002690 // Done handling.
2691 return;
2692 }
2693
2694 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002695 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002696 {
2697 // This is a tgkill()-based stop.
2698 if (thread_sp)
2699 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002700 if (log)
2701 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2702 __FUNCTION__,
2703 GetID (),
2704 pid);
2705
Chaoren Linaab58632015-02-03 01:50:57 +00002706 // Check that we're not already marked with a stop reason.
2707 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2708 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2709 // and that, without an intervening resume, we received another stop. It is more likely
2710 // that we are missing the marking of a run state somewhere if we find that the thread was
2711 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002712 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2713 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002714
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002715 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002716 if (!StateIsStoppedState (thread_state, false))
2717 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002718 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2719 // Generally, these are not important stops and we don't want to report them as
2720 // they are just used to stop other threads when one thread (the one with the
2721 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2722 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2723 // leave the signal intact if this is the thread that was chosen as the
2724 // triggering thread.
2725 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2726 linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2727 else
2728 linux_thread_sp->SetStoppedBySignal(0);
2729
Chaoren Linaab58632015-02-03 01:50:57 +00002730 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002731 NotifyThreadStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002732 }
2733 else
2734 {
2735 if (log)
2736 {
2737 // Retrieve the signal name if the thread was stopped by a signal.
2738 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002739 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002740 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2741 if (!signal_name)
2742 signal_name = "<no-signal-name>";
2743
2744 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",
2745 __FUNCTION__,
2746 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002747 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002748 StateAsCString (thread_state),
2749 stop_signo,
2750 signal_name);
2751 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002752 // Tell the thread state coordinator about the stop.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002753 NotifyThreadStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002754 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002755 }
2756
2757 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002758 return;
2759 }
2760
2761 if (log)
2762 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2763
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002764 // This thread is stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002765 NotifyThreadStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002766
Todd Fialaaf245d12014-06-30 21:05:18 +00002767 switch (signo)
2768 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002769 case SIGSTOP:
2770 {
2771 if (log)
2772 {
2773 if (is_from_llgs)
2774 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2775 else
2776 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2777 }
2778
Chaoren Linfa03ad22015-02-03 01:50:42 +00002779 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2780 // This thread will get stopped again as part of the group-stop completion.
Pavel Labathc0765592015-05-06 10:46:34 +00002781 RequestThreadResume (pid,
2782 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2783 {
2784 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2785 // Pass this signal number on to the inferior to handle.
2786 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002787 });
Todd Fiala511e5cd2014-09-11 23:29:14 +00002788 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002789 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002790 case SIGSEGV:
2791 case SIGILL:
2792 case SIGFPE:
2793 case SIGBUS:
2794 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002795 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002796 break;
2797 default:
2798 // This is just a pre-signal-delivery notification of the incoming signal.
2799 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002800 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002801
2802 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002803 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002804
2805 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002806 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002807}
2808
Tamas Berghammere7708682015-04-22 10:00:23 +00002809namespace {
2810
2811struct EmulatorBaton
2812{
2813 NativeProcessLinux* m_process;
2814 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002815
Pavel Labath6648fcc2015-04-27 09:21:14 +00002816 // eRegisterKindDWARF -> RegsiterValue
2817 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2818
2819 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002820 m_process(process), m_reg_context(reg_context) {}
2821};
2822
2823} // anonymous namespace
2824
2825static size_t
2826ReadMemoryCallback (EmulateInstruction *instruction,
2827 void *baton,
2828 const EmulateInstruction::Context &context,
2829 lldb::addr_t addr,
2830 void *dst,
2831 size_t length)
2832{
2833 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2834
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002835 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002836 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2837 return bytes_read;
2838}
2839
2840static bool
2841ReadRegisterCallback (EmulateInstruction *instruction,
2842 void *baton,
2843 const RegisterInfo *reg_info,
2844 RegisterValue &reg_value)
2845{
2846 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2847
Pavel Labath6648fcc2015-04-27 09:21:14 +00002848 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2849 if (it != emulator_baton->m_register_values.end())
2850 {
2851 reg_value = it->second;
2852 return true;
2853 }
2854
Tamas Berghammere7708682015-04-22 10:00:23 +00002855 // The emulator only fill in the dwarf regsiter numbers (and in some case
2856 // the generic register numbers). Get the full register info from the
2857 // register context based on the dwarf register numbers.
2858 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2859 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2860
2861 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002862 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002863 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002864
Pavel Labath6648fcc2015-04-27 09:21:14 +00002865 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002866}
2867
2868static bool
2869WriteRegisterCallback (EmulateInstruction *instruction,
2870 void *baton,
2871 const EmulateInstruction::Context &context,
2872 const RegisterInfo *reg_info,
2873 const RegisterValue &reg_value)
2874{
2875 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002876 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002877 return true;
2878}
2879
2880static size_t
2881WriteMemoryCallback (EmulateInstruction *instruction,
2882 void *baton,
2883 const EmulateInstruction::Context &context,
2884 lldb::addr_t addr,
2885 const void *dst,
2886 size_t length)
2887{
2888 return length;
2889}
2890
2891static lldb::addr_t
2892ReadFlags (NativeRegisterContext* regsiter_context)
2893{
2894 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2895 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2896 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2897}
2898
2899Error
2900NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2901{
2902 Error error;
2903 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2904
2905 std::unique_ptr<EmulateInstruction> emulator_ap(
2906 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2907
2908 if (emulator_ap == nullptr)
2909 return Error("Instruction emulator not found!");
2910
2911 EmulatorBaton baton(this, register_context_sp.get());
2912 emulator_ap->SetBaton(&baton);
2913 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2914 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2915 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2916 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2917
2918 if (!emulator_ap->ReadInstruction())
2919 return Error("Read instruction failed!");
2920
Pavel Labath6648fcc2015-04-27 09:21:14 +00002921 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2922
2923 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2924 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2925
2926 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2927 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2928
Tamas Berghammere7708682015-04-22 10:00:23 +00002929 lldb::addr_t next_pc;
2930 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002931 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002932 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002933 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2934 next_pc = pc_it->second.GetAsUInt64();
2935
2936 if (flags_it != baton.m_register_values.end())
2937 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002938 else
2939 next_flags = ReadFlags (register_context_sp.get());
2940 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002941 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002942 {
2943 // Emulate instruction failed and it haven't changed PC. Advance PC
2944 // with the size of the current opcode because the emulation of all
2945 // PC modifying instruction should be successful. The failure most
2946 // likely caused by a not supported instruction which don't modify PC.
2947 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2948 next_flags = ReadFlags (register_context_sp.get());
2949 }
2950 else
2951 {
2952 // The instruction emulation failed after it modified the PC. It is an
2953 // unknown error where we can't continue because the next instruction is
2954 // modifying the PC but we don't know how.
2955 return Error ("Instruction emulation failed unexpectedly.");
2956 }
2957
2958 if (m_arch.GetMachine() == llvm::Triple::arm)
2959 {
2960 if (next_flags & 0x20)
2961 {
2962 // Thumb mode
2963 error = SetSoftwareBreakpoint(next_pc, 2);
2964 }
2965 else
2966 {
2967 // Arm mode
2968 error = SetSoftwareBreakpoint(next_pc, 4);
2969 }
2970 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002971 else if (m_arch.GetMachine() == llvm::Triple::mips64
2972 || m_arch.GetMachine() == llvm::Triple::mips64el)
2973 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002974 else
2975 {
2976 // No size hint is given for the next breakpoint
2977 error = SetSoftwareBreakpoint(next_pc, 0);
2978 }
2979
Tamas Berghammere7708682015-04-22 10:00:23 +00002980 if (error.Fail())
2981 return error;
2982
2983 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2984
2985 return Error();
2986}
2987
2988bool
2989NativeProcessLinux::SupportHardwareSingleStepping() const
2990{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002991 if (m_arch.GetMachine() == llvm::Triple::arm
2992 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2993 return false;
2994 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002995}
2996
Todd Fialaaf245d12014-06-30 21:05:18 +00002997Error
2998NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2999{
Todd Fialaaf245d12014-06-30 21:05:18 +00003000 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3001 if (log)
3002 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
3003
Chaoren Lin03f12d62015-02-03 01:50:49 +00003004 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
3005 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00003006 int deferred_signo = 0;
3007 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003008 bool stepping = false;
Tamas Berghammere7708682015-04-22 10:00:23 +00003009 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00003010
Pavel Labath45f5cb32015-05-05 15:05:50 +00003011 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003012 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003013
Tamas Berghammere7708682015-04-22 10:00:23 +00003014 if (software_single_step)
3015 {
3016 for (auto thread_sp : m_threads)
3017 {
3018 assert (thread_sp && "thread list should not contain NULL threads");
3019
3020 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3021 if (action == nullptr)
3022 continue;
3023
3024 if (action->state == eStateStepping)
3025 {
3026 Error error = SetupSoftwareSingleStepping(thread_sp);
3027 if (error.Fail())
3028 return error;
3029 }
3030 }
3031 }
3032
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003033 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00003034 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003035 assert (thread_sp && "thread list should not contain NULL threads");
3036
3037 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3038
3039 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00003040 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00003041 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003042 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
3043 __FUNCTION__, GetID (), thread_sp->GetID ());
3044 continue;
3045 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003046
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003047 if (log)
3048 {
3049 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3050 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3051 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003052
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003053 switch (action->state)
3054 {
3055 case eStateRunning:
3056 {
3057 // Run the thread, possibly feeding it the signal.
3058 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003059 RequestThreadResumeAsNeeded (thread_sp->GetID (),
3060 [=](lldb::tid_t tid_to_resume, bool supress_signal)
3061 {
3062 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3063 // Pass this signal number on to the inferior to handle.
3064 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3065 if (resume_result.Success())
3066 SetState(eStateRunning, true);
3067 return resume_result;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003068 });
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003069 break;
3070 }
3071
3072 case eStateStepping:
3073 {
3074 // Request the step.
3075 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003076 RequestThreadResume (thread_sp->GetID (),
3077 [=](lldb::tid_t tid_to_step, bool supress_signal)
3078 {
3079 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00003080
Pavel Labathc0765592015-05-06 10:46:34 +00003081 Error step_result;
3082 if (software_single_step)
3083 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3084 else
3085 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00003086
Pavel Labathc0765592015-05-06 10:46:34 +00003087 assert (step_result.Success() && "SingleStep() failed");
3088 if (step_result.Success())
3089 SetState(eStateStepping, true);
3090 return step_result;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003091 });
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003092 stepping = true;
3093 break;
3094 }
3095
3096 case eStateSuspended:
3097 case eStateStopped:
3098 // if we haven't chosen a deferred signal tid yet, use this one.
3099 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00003100 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003101 deferred_signal_tid = thread_sp->GetID ();
3102 deferred_signal_thread_sp = thread_sp;
3103 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00003104 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003105 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00003106
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003107 default:
3108 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3109 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003110 }
3111 }
3112
Chaoren Linfa03ad22015-02-03 01:50:42 +00003113 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
3114 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003115 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
3116 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Pavel Labathed89c7f2015-05-06 12:22:37 +00003117 StopRunningThreadsWithSkipTID(deferred_signal_tid, deferred_signal_skip_tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00003118
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003119 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00003120}
3121
3122Error
3123NativeProcessLinux::Halt ()
3124{
3125 Error error;
3126
Todd Fialaaf245d12014-06-30 21:05:18 +00003127 if (kill (GetID (), SIGSTOP) != 0)
3128 error.SetErrorToErrno ();
3129
3130 return error;
3131}
3132
3133Error
3134NativeProcessLinux::Detach ()
3135{
3136 Error error;
3137
3138 // Tell ptrace to detach from the process.
3139 if (GetID () != LLDB_INVALID_PROCESS_ID)
3140 error = Detach (GetID ());
3141
3142 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00003143 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00003144
3145 // No error.
3146 return error;
3147}
3148
3149Error
3150NativeProcessLinux::Signal (int signo)
3151{
3152 Error error;
3153
3154 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3155 if (log)
3156 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3157 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3158
3159 if (kill(GetID(), signo))
3160 error.SetErrorToErrno();
3161
3162 return error;
3163}
3164
3165Error
Chaoren Line9547b82015-02-03 01:51:00 +00003166NativeProcessLinux::Interrupt ()
3167{
3168 // Pick a running thread (or if none, a not-dead stopped thread) as
3169 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00003170 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3171
3172 NativeThreadProtocolSP running_thread_sp;
3173 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003174
3175 if (log)
3176 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3177
Pavel Labath45f5cb32015-05-05 15:05:50 +00003178 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003179 Mutex::Locker locker (m_threads_mutex);
3180
3181 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00003182 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003183 // The thread shouldn't be null but lets just cover that here.
3184 if (!thread_sp)
3185 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00003186
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003187 // If we have a running or stepping thread, we'll call that the
3188 // target of the interrupt.
3189 const auto thread_state = thread_sp->GetState ();
3190 if (thread_state == eStateRunning ||
3191 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00003192 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003193 running_thread_sp = thread_sp;
3194 break;
3195 }
3196 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3197 {
3198 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
3199 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00003200 }
3201 }
3202
3203 if (!running_thread_sp && !stopped_thread_sp)
3204 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003205 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00003206 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00003207 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003208
Chaoren Line9547b82015-02-03 01:51:00 +00003209 return error;
3210 }
3211
3212 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3213
3214 if (log)
3215 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3216 __FUNCTION__,
3217 GetID (),
3218 running_thread_sp ? "running" : "stopped",
3219 deferred_signal_thread_sp->GetID ());
3220
Pavel Labathed89c7f2015-05-06 12:22:37 +00003221 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00003222
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003223 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00003224}
3225
3226Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003227NativeProcessLinux::Kill ()
3228{
3229 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3230 if (log)
3231 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3232
3233 Error error;
3234
3235 switch (m_state)
3236 {
3237 case StateType::eStateInvalid:
3238 case StateType::eStateExited:
3239 case StateType::eStateCrashed:
3240 case StateType::eStateDetached:
3241 case StateType::eStateUnloaded:
3242 // Nothing to do - the process is already dead.
3243 if (log)
3244 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3245 return error;
3246
3247 case StateType::eStateConnected:
3248 case StateType::eStateAttaching:
3249 case StateType::eStateLaunching:
3250 case StateType::eStateStopped:
3251 case StateType::eStateRunning:
3252 case StateType::eStateStepping:
3253 case StateType::eStateSuspended:
3254 // We can try to kill a process in these states.
3255 break;
3256 }
3257
3258 if (kill (GetID (), SIGKILL) != 0)
3259 {
3260 error.SetErrorToErrno ();
3261 return error;
3262 }
3263
3264 return error;
3265}
3266
3267static Error
3268ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3269{
3270 memory_region_info.Clear();
3271
3272 StringExtractor line_extractor (maps_line.c_str ());
3273
3274 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
3275 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
3276
3277 // Parse out the starting address
3278 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3279
3280 // Parse out hyphen separating start and end address from range.
3281 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3282 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3283
3284 // Parse out the ending address
3285 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3286
3287 // Parse out the space after the address.
3288 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3289 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3290
3291 // Save the range.
3292 memory_region_info.GetRange ().SetRangeBase (start_address);
3293 memory_region_info.GetRange ().SetRangeEnd (end_address);
3294
3295 // Parse out each permission entry.
3296 if (line_extractor.GetBytesLeft () < 4)
3297 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3298
3299 // Handle read permission.
3300 const char read_perm_char = line_extractor.GetChar ();
3301 if (read_perm_char == 'r')
3302 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3303 else
3304 {
3305 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3306 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3307 }
3308
3309 // Handle write permission.
3310 const char write_perm_char = line_extractor.GetChar ();
3311 if (write_perm_char == 'w')
3312 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3313 else
3314 {
3315 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3316 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3317 }
3318
3319 // Handle execute permission.
3320 const char exec_perm_char = line_extractor.GetChar ();
3321 if (exec_perm_char == 'x')
3322 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3323 else
3324 {
3325 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3326 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3327 }
3328
3329 return Error ();
3330}
3331
3332Error
3333NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3334{
3335 // FIXME review that the final memory region returned extends to the end of the virtual address space,
3336 // with no perms if it is not mapped.
3337
3338 // Use an approach that reads memory regions from /proc/{pid}/maps.
3339 // Assume proc maps entries are in ascending order.
3340 // FIXME assert if we find differently.
3341 Mutex::Locker locker (m_mem_region_cache_mutex);
3342
3343 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3344 Error error;
3345
3346 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3347 {
3348 // We're done.
3349 error.SetErrorString ("unsupported");
3350 return error;
3351 }
3352
3353 // If our cache is empty, pull the latest. There should always be at least one memory region
3354 // if memory region handling is supported.
3355 if (m_mem_region_cache.empty ())
3356 {
3357 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3358 [&] (const std::string &line) -> bool
3359 {
3360 MemoryRegionInfo info;
3361 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3362 if (parse_error.Success ())
3363 {
3364 m_mem_region_cache.push_back (info);
3365 return true;
3366 }
3367 else
3368 {
3369 if (log)
3370 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3371 return false;
3372 }
3373 });
3374
3375 // If we had an error, we'll mark unsupported.
3376 if (error.Fail ())
3377 {
3378 m_supports_mem_region = LazyBool::eLazyBoolNo;
3379 return error;
3380 }
3381 else if (m_mem_region_cache.empty ())
3382 {
3383 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3384 // is supported. Assume we don't support map entries via procfs.
3385 if (log)
3386 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3387 m_supports_mem_region = LazyBool::eLazyBoolNo;
3388 error.SetErrorString ("not supported");
3389 return error;
3390 }
3391
3392 if (log)
3393 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3394
3395 // We support memory retrieval, remember that.
3396 m_supports_mem_region = LazyBool::eLazyBoolYes;
3397 }
3398 else
3399 {
3400 if (log)
3401 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3402 }
3403
3404 lldb::addr_t prev_base_address = 0;
3405
3406 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3407 // There can be a ton of regions on pthreads apps with lots of threads.
3408 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3409 {
3410 MemoryRegionInfo &proc_entry_info = *it;
3411
3412 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3413 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3414 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3415
3416 // If the target address comes before this entry, indicate distance to next region.
3417 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3418 {
3419 range_info.GetRange ().SetRangeBase (load_addr);
3420 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3421 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3422 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3423 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3424
3425 return error;
3426 }
3427 else if (proc_entry_info.GetRange ().Contains (load_addr))
3428 {
3429 // The target address is within the memory region we're processing here.
3430 range_info = proc_entry_info;
3431 return error;
3432 }
3433
3434 // The target memory address comes somewhere after the region we just parsed.
3435 }
3436
3437 // If we made it here, we didn't find an entry that contained the given address.
3438 error.SetErrorString ("address comes after final region");
3439
3440 if (log)
3441 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3442
3443 return error;
3444}
3445
3446void
3447NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3448{
3449 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3450 if (log)
3451 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3452
3453 {
3454 Mutex::Locker locker (m_mem_region_cache_mutex);
3455 if (log)
3456 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3457 m_mem_region_cache.clear ();
3458 }
3459}
3460
3461Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003462NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00003463{
3464 // FIXME implementing this requires the equivalent of
3465 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3466 // functional ThreadPlans working with Native*Protocol.
3467#if 1
3468 return Error ("not implemented yet");
3469#else
3470 addr = LLDB_INVALID_ADDRESS;
3471
3472 unsigned prot = 0;
3473 if (permissions & lldb::ePermissionsReadable)
3474 prot |= eMmapProtRead;
3475 if (permissions & lldb::ePermissionsWritable)
3476 prot |= eMmapProtWrite;
3477 if (permissions & lldb::ePermissionsExecutable)
3478 prot |= eMmapProtExec;
3479
3480 // TODO implement this directly in NativeProcessLinux
3481 // (and lift to NativeProcessPOSIX if/when that class is
3482 // refactored out).
3483 if (InferiorCallMmap(this, addr, 0, size, prot,
3484 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3485 m_addr_to_mmap_size[addr] = size;
3486 return Error ();
3487 } else {
3488 addr = LLDB_INVALID_ADDRESS;
3489 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3490 }
3491#endif
3492}
3493
3494Error
3495NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3496{
3497 // FIXME see comments in AllocateMemory - required lower-level
3498 // bits not in place yet (ThreadPlans)
3499 return Error ("not implemented");
3500}
3501
3502lldb::addr_t
3503NativeProcessLinux::GetSharedLibraryInfoAddress ()
3504{
3505#if 1
3506 // punt on this for now
3507 return LLDB_INVALID_ADDRESS;
3508#else
3509 // Return the image info address for the exe module
3510#if 1
3511 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3512
3513 ModuleSP module_sp;
3514 Error error = GetExeModuleSP (module_sp);
3515 if (error.Fail ())
3516 {
3517 if (log)
3518 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3519 return LLDB_INVALID_ADDRESS;
3520 }
3521
3522 if (module_sp == nullptr)
3523 {
3524 if (log)
3525 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3526 return LLDB_INVALID_ADDRESS;
3527 }
3528
3529 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3530 if (object_file_sp == nullptr)
3531 {
3532 if (log)
3533 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3534 return LLDB_INVALID_ADDRESS;
3535 }
3536
3537 return obj_file_sp->GetImageInfoAddress();
3538#else
3539 Target *target = &GetTarget();
3540 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3541 Address addr = obj_file->GetImageInfoAddress(target);
3542
3543 if (addr.IsValid())
3544 return addr.GetLoadAddress(target);
3545 return LLDB_INVALID_ADDRESS;
3546#endif
3547#endif // punt on this for now
3548}
3549
3550size_t
3551NativeProcessLinux::UpdateThreads ()
3552{
3553 // The NativeProcessLinux monitoring threads are always up to date
3554 // with respect to thread state and they keep the thread list
3555 // populated properly. All this method needs to do is return the
3556 // thread count.
3557 Mutex::Locker locker (m_threads_mutex);
3558 return m_threads.size ();
3559}
3560
3561bool
3562NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3563{
3564 arch = m_arch;
3565 return true;
3566}
3567
3568Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003569NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003570{
3571 // FIXME put this behind a breakpoint protocol class that can be
3572 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003573 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003574 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003575 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003576
3577 switch (m_arch.GetMachine ())
3578 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003579 case llvm::Triple::aarch64:
3580 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3581 return Error ();
3582
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003583 case llvm::Triple::arm:
3584 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3585 return Error ();
3586
Todd Fialaaf245d12014-06-30 21:05:18 +00003587 case llvm::Triple::x86:
3588 case llvm::Triple::x86_64:
3589 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3590 return Error ();
3591
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003592 case llvm::Triple::mips64:
3593 case llvm::Triple::mips64el:
3594 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3595 return Error ();
3596
Todd Fialaaf245d12014-06-30 21:05:18 +00003597 default:
3598 assert(false && "CPU type not supported!");
3599 return Error ("CPU type not supported");
3600 }
3601}
3602
3603Error
3604NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3605{
3606 if (hardware)
3607 return Error ("NativeProcessLinux does not support hardware breakpoints");
3608 else
3609 return SetSoftwareBreakpoint (addr, size);
3610}
3611
3612Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003613NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3614 size_t &actual_opcode_size,
3615 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003616{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003617 // FIXME put this behind a breakpoint protocol class that can be set per
3618 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003619 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003620 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3621 // linux kernel does otherwise.
3622 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003623 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003624 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003625 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003626 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003627
3628 switch (m_arch.GetMachine ())
3629 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003630 case llvm::Triple::aarch64:
3631 trap_opcode_bytes = g_aarch64_opcode;
3632 actual_opcode_size = sizeof(g_aarch64_opcode);
3633 return Error ();
3634
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003635 case llvm::Triple::arm:
3636 switch (trap_opcode_size_hint)
3637 {
3638 case 2:
3639 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3640 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3641 return Error ();
3642 case 4:
3643 trap_opcode_bytes = g_arm_breakpoint_opcode;
3644 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3645 return Error ();
3646 default:
3647 assert(false && "Unrecognised trap opcode size hint!");
3648 return Error ("Unrecognised trap opcode size hint!");
3649 }
3650
Todd Fialaaf245d12014-06-30 21:05:18 +00003651 case llvm::Triple::x86:
3652 case llvm::Triple::x86_64:
3653 trap_opcode_bytes = g_i386_opcode;
3654 actual_opcode_size = sizeof(g_i386_opcode);
3655 return Error ();
3656
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003657 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003658 trap_opcode_bytes = g_mips64_opcode;
3659 actual_opcode_size = sizeof(g_mips64_opcode);
3660 return Error ();
3661
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003662 case llvm::Triple::mips64el:
3663 trap_opcode_bytes = g_mips64el_opcode;
3664 actual_opcode_size = sizeof(g_mips64el_opcode);
3665 return Error ();
3666
Todd Fialaaf245d12014-06-30 21:05:18 +00003667 default:
3668 assert(false && "CPU type not supported!");
3669 return Error ("CPU type not supported");
3670 }
3671}
3672
3673#if 0
3674ProcessMessage::CrashReason
3675NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3676{
3677 ProcessMessage::CrashReason reason;
3678 assert(info->si_signo == SIGSEGV);
3679
3680 reason = ProcessMessage::eInvalidCrashReason;
3681
3682 switch (info->si_code)
3683 {
3684 default:
3685 assert(false && "unexpected si_code for SIGSEGV");
3686 break;
3687 case SI_KERNEL:
3688 // Linux will occasionally send spurious SI_KERNEL codes.
3689 // (this is poorly documented in sigaction)
3690 // One way to get this is via unaligned SIMD loads.
3691 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3692 break;
3693 case SEGV_MAPERR:
3694 reason = ProcessMessage::eInvalidAddress;
3695 break;
3696 case SEGV_ACCERR:
3697 reason = ProcessMessage::ePrivilegedAddress;
3698 break;
3699 }
3700
3701 return reason;
3702}
3703#endif
3704
3705
3706#if 0
3707ProcessMessage::CrashReason
3708NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3709{
3710 ProcessMessage::CrashReason reason;
3711 assert(info->si_signo == SIGILL);
3712
3713 reason = ProcessMessage::eInvalidCrashReason;
3714
3715 switch (info->si_code)
3716 {
3717 default:
3718 assert(false && "unexpected si_code for SIGILL");
3719 break;
3720 case ILL_ILLOPC:
3721 reason = ProcessMessage::eIllegalOpcode;
3722 break;
3723 case ILL_ILLOPN:
3724 reason = ProcessMessage::eIllegalOperand;
3725 break;
3726 case ILL_ILLADR:
3727 reason = ProcessMessage::eIllegalAddressingMode;
3728 break;
3729 case ILL_ILLTRP:
3730 reason = ProcessMessage::eIllegalTrap;
3731 break;
3732 case ILL_PRVOPC:
3733 reason = ProcessMessage::ePrivilegedOpcode;
3734 break;
3735 case ILL_PRVREG:
3736 reason = ProcessMessage::ePrivilegedRegister;
3737 break;
3738 case ILL_COPROC:
3739 reason = ProcessMessage::eCoprocessorError;
3740 break;
3741 case ILL_BADSTK:
3742 reason = ProcessMessage::eInternalStackError;
3743 break;
3744 }
3745
3746 return reason;
3747}
3748#endif
3749
3750#if 0
3751ProcessMessage::CrashReason
3752NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3753{
3754 ProcessMessage::CrashReason reason;
3755 assert(info->si_signo == SIGFPE);
3756
3757 reason = ProcessMessage::eInvalidCrashReason;
3758
3759 switch (info->si_code)
3760 {
3761 default:
3762 assert(false && "unexpected si_code for SIGFPE");
3763 break;
3764 case FPE_INTDIV:
3765 reason = ProcessMessage::eIntegerDivideByZero;
3766 break;
3767 case FPE_INTOVF:
3768 reason = ProcessMessage::eIntegerOverflow;
3769 break;
3770 case FPE_FLTDIV:
3771 reason = ProcessMessage::eFloatDivideByZero;
3772 break;
3773 case FPE_FLTOVF:
3774 reason = ProcessMessage::eFloatOverflow;
3775 break;
3776 case FPE_FLTUND:
3777 reason = ProcessMessage::eFloatUnderflow;
3778 break;
3779 case FPE_FLTRES:
3780 reason = ProcessMessage::eFloatInexactResult;
3781 break;
3782 case FPE_FLTINV:
3783 reason = ProcessMessage::eFloatInvalidOperation;
3784 break;
3785 case FPE_FLTSUB:
3786 reason = ProcessMessage::eFloatSubscriptRange;
3787 break;
3788 }
3789
3790 return reason;
3791}
3792#endif
3793
3794#if 0
3795ProcessMessage::CrashReason
3796NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3797{
3798 ProcessMessage::CrashReason reason;
3799 assert(info->si_signo == SIGBUS);
3800
3801 reason = ProcessMessage::eInvalidCrashReason;
3802
3803 switch (info->si_code)
3804 {
3805 default:
3806 assert(false && "unexpected si_code for SIGBUS");
3807 break;
3808 case BUS_ADRALN:
3809 reason = ProcessMessage::eIllegalAlignment;
3810 break;
3811 case BUS_ADRERR:
3812 reason = ProcessMessage::eIllegalAddress;
3813 break;
3814 case BUS_OBJERR:
3815 reason = ProcessMessage::eHardwareError;
3816 break;
3817 }
3818
3819 return reason;
3820}
3821#endif
3822
Todd Fialaaf245d12014-06-30 21:05:18 +00003823Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003824NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3825{
3826 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3827 // for it.
3828 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3829 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3830}
3831
3832Error
3833NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3834{
3835 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3836 // for it.
3837 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3838 return NativeProcessProtocol::RemoveWatchpoint(addr);
3839}
3840
3841Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003842NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003843{
3844 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003845 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003846 return op.GetError ();
3847}
3848
3849Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003850NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3851{
3852 Error error = ReadMemory(addr, buf, size, bytes_read);
3853 if (error.Fail()) return error;
3854 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3855}
3856
3857Error
3858NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003859{
3860 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003861 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003862 return op.GetError ();
3863}
3864
Chaoren Lin97ccc292015-02-03 01:51:12 +00003865Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003866NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003867 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003868{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003869 ReadRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003870 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003871 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003872}
3873
Chaoren Lin97ccc292015-02-03 01:51:12 +00003874Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003875NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3876 const char* reg_name, const RegisterValue &value)
3877{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003878 WriteRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003879 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003880 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003881}
3882
Chaoren Lin97ccc292015-02-03 01:51:12 +00003883Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003884NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3885{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003886 ReadGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003887 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003888 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003889}
3890
Chaoren Lin97ccc292015-02-03 01:51:12 +00003891Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003892NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3893{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003894 ReadFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003895 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003896 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003897}
3898
Chaoren Lin97ccc292015-02-03 01:51:12 +00003899Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003900NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3901{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003902 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003903 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003904 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003905}
3906
Chaoren Lin97ccc292015-02-03 01:51:12 +00003907Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003908NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3909{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003910 WriteGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003911 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003912 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003913}
3914
Chaoren Lin97ccc292015-02-03 01:51:12 +00003915Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003916NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3917{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003918 WriteFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003919 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003920 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003921}
3922
Chaoren Lin97ccc292015-02-03 01:51:12 +00003923Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003924NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3925{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003926 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003927 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003928 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003929}
3930
Chaoren Lin97ccc292015-02-03 01:51:12 +00003931Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003932NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3933{
Todd Fialaaf245d12014-06-30 21:05:18 +00003934 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3935
3936 if (log)
3937 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3938 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003939 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003940 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003941 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003942 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3943 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003944}
3945
Chaoren Lin97ccc292015-02-03 01:51:12 +00003946Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003947NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3948{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003949 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003950 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003951 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003952}
3953
Chaoren Lin97ccc292015-02-03 01:51:12 +00003954Error
3955NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003956{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003957 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003958 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003959 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003960}
3961
Chaoren Lin97ccc292015-02-03 01:51:12 +00003962Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003963NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3964{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003965 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003966 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003967 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003968}
3969
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003970Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003971NativeProcessLinux::Detach(lldb::tid_t tid)
3972{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003973 if (tid == LLDB_INVALID_THREAD_ID)
3974 return Error();
3975
3976 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003977 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003978 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003979}
3980
3981bool
3982NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3983{
3984 int target_fd = open(path, flags, 0666);
3985
3986 if (target_fd == -1)
3987 return false;
3988
Pavel Labath493c3a12015-02-04 10:36:57 +00003989 if (dup2(target_fd, fd) == -1)
3990 return false;
3991
3992 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003993}
3994
3995void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003996NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003997{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003998 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003999 error = m_monitor_up->Initialize();
4000 if (error.Fail()) {
4001 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00004002 }
4003}
4004
Todd Fialaaf245d12014-06-30 21:05:18 +00004005bool
4006NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
4007{
4008 for (auto thread_sp : m_threads)
4009 {
4010 assert (thread_sp && "thread list should not contain NULL threads");
4011 if (thread_sp->GetID () == thread_id)
4012 {
4013 // We have this thread.
4014 return true;
4015 }
4016 }
4017
4018 // We don't have this thread.
4019 return false;
4020}
4021
4022NativeThreadProtocolSP
4023NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4024{
4025 // CONSIDER organize threads by map - we can do better than linear.
4026 for (auto thread_sp : m_threads)
4027 {
4028 if (thread_sp->GetID () == thread_id)
4029 return thread_sp;
4030 }
4031
4032 // We don't have this thread.
4033 return NativeThreadProtocolSP ();
4034}
4035
4036bool
4037NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4038{
4039 Mutex::Locker locker (m_threads_mutex);
4040 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4041 {
4042 if (*it && ((*it)->GetID () == thread_id))
4043 {
4044 m_threads.erase (it);
4045 return true;
4046 }
4047 }
4048
4049 // Didn't find it.
4050 return false;
4051}
4052
4053NativeThreadProtocolSP
4054NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4055{
4056 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4057
4058 Mutex::Locker locker (m_threads_mutex);
4059
4060 if (log)
4061 {
4062 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4063 __FUNCTION__,
4064 GetID (),
4065 thread_id);
4066 }
4067
4068 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4069
4070 // If this is the first thread, save it as the current thread
4071 if (m_threads.empty ())
4072 SetCurrentThreadID (thread_id);
4073
4074 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4075 m_threads.push_back (thread_sp);
4076
4077 return thread_sp;
4078}
4079
Todd Fialaaf245d12014-06-30 21:05:18 +00004080Error
4081NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4082{
Todd Fiala75f47c32014-10-11 21:42:09 +00004083 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00004084
4085 Error error;
4086
4087 // Get a linux thread pointer.
4088 if (!thread_sp)
4089 {
4090 error.SetErrorString ("null thread_sp");
4091 if (log)
4092 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4093 return error;
4094 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004095 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00004096
4097 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004098 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00004099 if (!context_sp)
4100 {
4101 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4102 if (log)
4103 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4104 return error;
4105 }
4106
4107 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00004108 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00004109 if (error.Fail ())
4110 {
4111 if (log)
4112 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4113 return error;
4114 }
4115 else
4116 {
4117 if (log)
4118 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4119 }
4120
4121 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4122 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4123 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004124 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00004125 {
4126 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004127 if (breakpoint_addr >= breakpoint_size)
4128 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00004129 }
4130
4131 // Check if we stopped because of a breakpoint.
4132 NativeBreakpointSP breakpoint_sp;
4133 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4134 if (!error.Success () || !breakpoint_sp)
4135 {
4136 // We didn't find one at a software probe location. Nothing to do.
4137 if (log)
4138 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4139 return Error ();
4140 }
4141
4142 // If the breakpoint is not a software breakpoint, nothing to do.
4143 if (!breakpoint_sp->IsSoftwareBreakpoint ())
4144 {
4145 if (log)
4146 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4147 return Error ();
4148 }
4149
4150 //
4151 // We have a software breakpoint and need to adjust the PC.
4152 //
4153
4154 // Sanity check.
4155 if (breakpoint_size == 0)
4156 {
4157 // Nothing to do! How did we get here?
4158 if (log)
4159 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);
4160 return Error ();
4161 }
4162
4163 // Change the program counter.
4164 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004165 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 +00004166
4167 error = context_sp->SetPC (breakpoint_addr);
4168 if (error.Fail ())
4169 {
4170 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004171 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 +00004172 return error;
4173 }
4174
4175 return error;
4176}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004177
4178void
4179NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
4180{
4181 const bool is_stopped = true;
Pavel Labath5eb721e2015-05-07 08:30:31 +00004182 NotifyThreadCreate (tid, is_stopped);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004183}
4184
4185void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004186NativeProcessLinux::StopRunningThreads(lldb::tid_t trigerring_tid)
Chaoren Linfa03ad22015-02-03 01:50:42 +00004187{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004188 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4189 if (log)
Pavel Labathed89c7f2015-05-06 12:22:37 +00004190 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, trigerring_tid);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004191
Chaoren Linfa03ad22015-02-03 01:50:42 +00004192 const lldb::pid_t pid = GetID ();
Pavel Labathed89c7f2015-05-06 12:22:37 +00004193 StopRunningThreads(trigerring_tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004194 [=](lldb::tid_t request_stop_tid) { return RequestThreadStop(pid, request_stop_tid); });
Chaoren Lin03f12d62015-02-03 01:50:49 +00004195}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004196
Chaoren Lin03f12d62015-02-03 01:50:49 +00004197void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004198NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t deferred_signal_tid,
4199 lldb::tid_t skip_stop_request_tid)
Chaoren Lin03f12d62015-02-03 01:50:49 +00004200{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004201 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4202 if (log)
4203 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
4204
Chaoren Lin03f12d62015-02-03 01:50:49 +00004205 const lldb::pid_t pid = GetID ();
Pavel Labathed89c7f2015-05-06 12:22:37 +00004206 StopRunningThreadsWithSkipTID(deferred_signal_tid,
Pavel Labathc0765592015-05-06 10:46:34 +00004207 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : NativeProcessLinux::ThreadIDSet (),
Pavel Labath5eb721e2015-05-07 08:30:31 +00004208 [=](lldb::tid_t request_stop_tid) { return RequestThreadStop(pid, request_stop_tid); });
Chaoren Linfa03ad22015-02-03 01:50:42 +00004209}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004210
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004211Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004212NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
4213{
4214 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4215 if (log)
4216 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
4217
4218 Error err;
4219 errno = 0;
4220 if (::tgkill (pid, tid, SIGSTOP) != 0)
4221 {
4222 err.SetErrorToErrno ();
4223 if (log)
4224 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
4225 }
4226
4227 return err;
4228}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004229
4230Error
4231NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4232{
4233 char maps_file_name[32];
4234 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4235
4236 FileSpec maps_file_spec(maps_file_name, false);
4237 if (!maps_file_spec.Exists()) {
4238 file_spec.Clear();
4239 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4240 }
4241
4242 FileSpec module_file_spec(module_path, true);
4243
4244 std::ifstream maps_file(maps_file_name);
4245 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4246 StringRef maps_data(maps_data_str.c_str());
4247
4248 while (!maps_data.empty())
4249 {
4250 StringRef maps_row;
4251 std::tie(maps_row, maps_data) = maps_data.split('\n');
4252
4253 SmallVector<StringRef, 16> maps_columns;
4254 maps_row.split(maps_columns, StringRef(" "), -1, false);
4255
4256 if (maps_columns.size() >= 6)
4257 {
4258 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4259 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4260 return Error();
4261 }
4262 }
4263
4264 file_spec.Clear();
4265 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4266 module_file_spec.GetFilename().AsCString(), GetID());
4267}
Pavel Labathc0765592015-05-06 10:46:34 +00004268
Pavel Labath5eb721e2015-05-07 08:30:31 +00004269Error
Pavel Labathc0765592015-05-06 10:46:34 +00004270NativeProcessLinux::DoResume(
4271 lldb::tid_t tid,
4272 ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00004273 bool error_when_already_running)
4274{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004275 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4276
Pavel Labathc0765592015-05-06 10:46:34 +00004277 auto find_it = m_tid_map.find (tid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004278 lldbassert(find_it != m_tid_map.end ()); // Ensure we know about the thread.
4279
Pavel Labathc0765592015-05-06 10:46:34 +00004280 auto& context = find_it->second;
4281 // Tell the thread to resume if we don't already think it is running.
4282 const bool is_stopped = context.m_state == ThreadState::Stopped;
Pavel Labath5eb721e2015-05-07 08:30:31 +00004283
4284 lldbassert(!(error_when_already_running && !is_stopped));
4285
Pavel Labathc0765592015-05-06 10:46:34 +00004286 if (!is_stopped)
4287 {
4288 // It's not an error, just a log, if the error_when_already_running flag is not set.
4289 // This covers cases where, for instance, we're just trying to resume all threads
4290 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004291 if (log)
4292 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4293 __FUNCTION__,
4294 tid);
4295 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00004296 }
4297
4298 // Before we do the resume below, first check if we have a pending
4299 // stop notification this is currently or was previously waiting for
4300 // this thread to stop. This is potentially a buggy situation since
4301 // we're ostensibly waiting for threads to stop before we send out the
4302 // pending notification, and here we are resuming one before we send
4303 // out the pending stop notification.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004304 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004305 {
4306 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4307 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004308 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004309 }
4310 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0)
4311 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004312 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that hasn't fired yet and this is one of the threads we had been waiting on (and already marked satisfied for this tid). Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004313 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4314 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004315 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00004316 __FUNCTION__,
4317 m_pending_notification_up->triggering_tid,
4318 tid);
4319 }
4320 }
4321 }
4322
4323 // Request a resume. We expect this to be synchronous and the system
4324 // to reflect it is running after this completes.
4325 const auto error = request_thread_resume_function (tid, false);
4326 if (error.Success ())
4327 {
4328 // Now mark it is running.
4329 context.m_state = ThreadState::Running;
4330 context.m_request_resume_function = request_thread_resume_function;
4331 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004332 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004333 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004334 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00004335 __FUNCTION__, tid, error.AsCString ());
4336 }
4337
Pavel Labath5eb721e2015-05-07 08:30:31 +00004338 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004339}
4340
4341//===----------------------------------------------------------------------===//
4342
4343void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004344NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid,
Pavel Labathc0765592015-05-06 10:46:34 +00004345 const ThreadIDSet &wait_for_stop_tids,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004346 const StopThreadFunction &request_thread_stop_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004347{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004348 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004349 std::lock_guard<std::mutex> lock(m_event_mutex);
4350
Pavel Labath5eb721e2015-05-07 08:30:31 +00004351 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004352 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004353 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)",
Pavel Labathc0765592015-05-06 10:46:34 +00004354 __FUNCTION__, triggering_tid, wait_for_stop_tids.size());
4355 }
4356
Pavel Labathed89c7f2015-05-06 12:22:37 +00004357 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labath5eb721e2015-05-07 08:30:31 +00004358 triggering_tid, wait_for_stop_tids, request_thread_stop_function)));
Pavel Labathc0765592015-05-06 10:46:34 +00004359
Pavel Labath5eb721e2015-05-07 08:30:31 +00004360 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004361 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004362 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004363 }
4364}
4365
4366void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004367NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004368 const StopThreadFunction &request_thread_stop_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004369{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004370 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004371 std::lock_guard<std::mutex> lock(m_event_mutex);
4372
Pavel Labath5eb721e2015-05-07 08:30:31 +00004373 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004374 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004375 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004376 __FUNCTION__, triggering_tid);
4377 }
4378
Pavel Labathed89c7f2015-05-06 12:22:37 +00004379 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labathc0765592015-05-06 10:46:34 +00004380 triggering_tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004381 request_thread_stop_function)));
Pavel Labathc0765592015-05-06 10:46:34 +00004382
Pavel Labath5eb721e2015-05-07 08:30:31 +00004383 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004384 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004385 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004386 }
4387}
4388
4389void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004390NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid,
Pavel Labathc0765592015-05-06 10:46:34 +00004391 const ThreadIDSet &skip_stop_request_tids,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004392 const StopThreadFunction &request_thread_stop_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004393{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004394 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004395 std::lock_guard<std::mutex> lock(m_event_mutex);
4396
Pavel Labath5eb721e2015-05-07 08:30:31 +00004397 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004398 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004399 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tids.size(): %zd)",
Pavel Labathc0765592015-05-06 10:46:34 +00004400 __FUNCTION__, triggering_tid, skip_stop_request_tids.size());
4401 }
4402
Pavel Labathed89c7f2015-05-06 12:22:37 +00004403 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labathc0765592015-05-06 10:46:34 +00004404 triggering_tid,
4405 request_thread_stop_function,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004406 skip_stop_request_tids)));
Pavel Labathc0765592015-05-06 10:46:34 +00004407
Pavel Labath5eb721e2015-05-07 08:30:31 +00004408 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004409 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004410 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004411 }
4412}
4413
4414void
4415NativeProcessLinux::SignalIfRequirementsSatisfied()
4416{
4417 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4418 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00004419 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4420 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004421 m_pending_notification_up.reset();
4422 }
4423}
4424
4425bool
4426NativeProcessLinux::RequestStopOnAllSpecifiedThreads()
4427{
4428 // Request a stop for all the thread stops that need to be stopped
4429 // and are not already known to be stopped. Keep a list of all the
4430 // threads from which we still need to hear a stop reply.
4431
4432 ThreadIDSet sent_tids;
4433 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4434 {
4435 // Validate we know about all tids for which we must first receive a stop before
4436 // triggering the deferred stop notification.
4437 auto find_it = m_tid_map.find (tid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004438 lldbassert(find_it != m_tid_map.end());
Pavel Labathc0765592015-05-06 10:46:34 +00004439
4440 // If the pending stop thread is currently running, we need to send it a stop request.
4441 auto& context = find_it->second;
4442 if (context.m_state == ThreadState::Running)
4443 {
4444 RequestThreadStop (tid, context);
4445 sent_tids.insert (tid);
4446 }
4447 }
4448 // We only need to wait for the sent_tids - so swap our wait set
4449 // to the sent tids. The rest are already stopped and we won't
4450 // be receiving stop notifications for them.
4451 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4452
4453 // Succeeded, keep running.
4454 return true;
4455}
4456
4457void
4458NativeProcessLinux::RequestStopOnAllRunningThreads()
4459{
4460 // Request a stop for all the thread stops that need to be stopped
4461 // and are not already known to be stopped. Keep a list of all the
4462 // threads from which we still need to hear a stop reply.
4463
4464 ThreadIDSet sent_tids;
4465 for (auto it = m_tid_map.begin(); it != m_tid_map.end(); ++it)
4466 {
4467 // We only care about threads not stopped.
4468 const bool running = it->second.m_state == ThreadState::Running;
4469 if (running)
4470 {
4471 const lldb::tid_t tid = it->first;
4472
4473 // Request this thread stop if the tid stop request is not explicitly ignored.
4474 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0;
4475 if (!skip_stop_request)
4476 RequestThreadStop (tid, it->second);
4477
4478 // Even if we skipped sending the stop request for other reasons (like stepping),
4479 // we still need to wait for that stepping thread to notify completion/stop.
4480 sent_tids.insert (tid);
4481 }
4482 }
4483
4484 // Set the wait list to the set of tids for which we requested stops.
4485 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4486}
4487
4488void
4489NativeProcessLinux::RequestThreadStop (lldb::tid_t tid, ThreadContext& context)
4490{
4491 const auto error = m_pending_notification_up->request_thread_stop_function (tid);
4492 if (error.Success ())
4493 context.m_stop_requested = true;
4494 else
4495 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004496 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4497 if (log)
4498 log->Printf("NativeProcessLinux::%s failed to request thread stop tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00004499 __FUNCTION__, tid, error.AsCString ());
4500 }
4501}
4502
4503
Pavel Labath5eb721e2015-05-07 08:30:31 +00004504Error
4505NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004506{
4507 // Ensure we know about the thread.
4508 auto find_it = m_tid_map.find (tid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004509 lldbassert(find_it != m_tid_map.end());
Pavel Labathc0765592015-05-06 10:46:34 +00004510
4511 // Update the global list of known thread states. This one is definitely stopped.
4512 auto& context = find_it->second;
4513 const auto stop_was_requested = context.m_stop_requested;
4514 context.m_state = ThreadState::Stopped;
4515 context.m_stop_requested = false;
4516
4517 // If we have a pending notification, remove this from the set.
4518 if (m_pending_notification_up)
4519 {
4520 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4521 SignalIfRequirementsSatisfied();
4522 }
4523
4524 if (initiated_by_llgs && context.m_request_resume_function && !stop_was_requested)
4525 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004526 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004527 // We can end up here if stop was initiated by LLGS but by this time a
4528 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004529 if (log)
4530 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004531 const auto error = context.m_request_resume_function (tid, true);
4532 if (error.Success ())
4533 {
4534 context.m_state = ThreadState::Running;
4535 }
4536 else
4537 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004538 if (log)
4539 {
4540 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
4541 __FUNCTION__, tid, error.AsCString ());
4542 }
4543 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004544 }
4545 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004546 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00004547}
4548
4549void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004550NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00004551{
4552 // Validate we know about the deferred trigger thread.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004553 lldbassert(IsKnownThread (notification_up->triggering_tid));
Pavel Labathc0765592015-05-06 10:46:34 +00004554
Pavel Labath5eb721e2015-05-07 08:30:31 +00004555 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4556 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004557 {
4558 // Yikes - we've already got a pending signal notification in progress.
4559 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004560 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00004561 __FUNCTION__,
4562 m_pending_notification_up->triggering_tid,
4563 notification_up->triggering_tid);
4564 }
4565 m_pending_notification_up = std::move(notification_up);
4566
4567 if (m_pending_notification_up->request_stop_on_all_unstopped_threads)
4568 RequestStopOnAllRunningThreads();
4569 else
4570 {
4571 if (!RequestStopOnAllSpecifiedThreads())
4572 return;
4573 }
4574
Pavel Labathed89c7f2015-05-06 12:22:37 +00004575 SignalIfRequirementsSatisfied();
Pavel Labathc0765592015-05-06 10:46:34 +00004576}
4577
4578void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004579NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid, bool is_stopped)
Pavel Labathc0765592015-05-06 10:46:34 +00004580{
4581 // Ensure we don't already know about the thread.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004582 lldbassert(m_tid_map.find(tid) == m_tid_map.end());
Pavel Labathc0765592015-05-06 10:46:34 +00004583
4584 // Add the new thread to the stop map.
4585 ThreadContext ctx;
4586 ctx.m_state = (is_stopped) ? ThreadState::Stopped : ThreadState::Running;
4587 m_tid_map[tid] = std::move(ctx);
4588
4589 if (m_pending_notification_up && !is_stopped)
4590 {
4591 // We will need to wait for this new thread to stop as well before firing the
4592 // notification.
4593 m_pending_notification_up->wait_for_stop_tids.insert(tid);
4594 m_pending_notification_up->request_thread_stop_function(tid);
4595 }
4596}
4597
4598void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004599NativeProcessLinux::ThreadDidDie (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004600{
4601 // Ensure we know about the thread.
4602 auto find_it = m_tid_map.find (tid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004603 lldbassert(find_it != m_tid_map.end());
Pavel Labathc0765592015-05-06 10:46:34 +00004604
4605 // Update the global list of known thread states. While this one is stopped, it is also dead.
4606 // So stop tracking it. We assume the user of this coordinator will not keep trying to add
4607 // dependencies on a thread after it is known to be dead.
4608 m_tid_map.erase (find_it);
4609
4610 // If we have a pending notification, remove this from the set.
4611 if (m_pending_notification_up)
4612 {
4613 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4614 SignalIfRequirementsSatisfied();
4615 }
4616}
4617
Pavel Labath5eb721e2015-05-07 08:30:31 +00004618Error
4619NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004620{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004621 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004622 std::lock_guard<std::mutex> lock(m_event_mutex);
4623
Pavel Labath5eb721e2015-05-07 08:30:31 +00004624 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004625 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004626 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)",
Pavel Labathc0765592015-05-06 10:46:34 +00004627 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
4628 }
4629
Pavel Labath5eb721e2015-05-07 08:30:31 +00004630 Error error = ThreadDidStop (tid, initiated_by_llgs);
Pavel Labathc0765592015-05-06 10:46:34 +00004631
Pavel Labath5eb721e2015-05-07 08:30:31 +00004632 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004633 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004634 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004635 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004636
4637 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004638}
4639
Pavel Labath5eb721e2015-05-07 08:30:31 +00004640Error
Pavel Labathc0765592015-05-06 10:46:34 +00004641NativeProcessLinux::RequestThreadResume (lldb::tid_t tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004642 const ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004643{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004644 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004645 std::lock_guard<std::mutex> lock(m_event_mutex);
4646
Pavel Labath5eb721e2015-05-07 08:30:31 +00004647 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004648 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004649 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004650 __FUNCTION__, tid);
4651 }
4652
Pavel Labath5eb721e2015-05-07 08:30:31 +00004653 Error error = DoResume(tid, request_thread_resume_function, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004654
Pavel Labath5eb721e2015-05-07 08:30:31 +00004655 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004656 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004657 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004658 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004659
4660 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004661}
4662
Pavel Labath5eb721e2015-05-07 08:30:31 +00004663Error
Pavel Labathc0765592015-05-06 10:46:34 +00004664NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004665 const ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004666{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004667 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004668 std::lock_guard<std::mutex> lock(m_event_mutex);
4669
Pavel Labath5eb721e2015-05-07 08:30:31 +00004670 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004671 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004672 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004673 __FUNCTION__, tid);
4674 }
4675
Pavel Labath5eb721e2015-05-07 08:30:31 +00004676 Error error = DoResume (tid, request_thread_resume_function, false);
Pavel Labathc0765592015-05-06 10:46:34 +00004677
Pavel Labath5eb721e2015-05-07 08:30:31 +00004678 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004679 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004680 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004681 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004682
4683 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004684}
4685
4686void
4687NativeProcessLinux::NotifyThreadCreate (lldb::tid_t tid,
Pavel Labath5eb721e2015-05-07 08:30:31 +00004688 bool is_stopped)
Pavel Labathc0765592015-05-06 10:46:34 +00004689{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004690 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004691 std::lock_guard<std::mutex> lock(m_event_mutex);
4692
Pavel Labath5eb721e2015-05-07 08:30:31 +00004693 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004694 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004695 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", is %sstopped)",
Pavel Labathc0765592015-05-06 10:46:34 +00004696 __FUNCTION__, tid, is_stopped?"":"not ");
4697 }
4698
Pavel Labath5eb721e2015-05-07 08:30:31 +00004699 ThreadWasCreated (tid, is_stopped);
Pavel Labathc0765592015-05-06 10:46:34 +00004700
Pavel Labath5eb721e2015-05-07 08:30:31 +00004701 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004702 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004703 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004704 }
4705}
4706
4707void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004708NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004709{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004710 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004711 std::lock_guard<std::mutex> lock(m_event_mutex);
4712
Pavel Labath5eb721e2015-05-07 08:30:31 +00004713 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004714 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004715 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004716 }
4717
Pavel Labath5eb721e2015-05-07 08:30:31 +00004718 ThreadDidDie(tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004719
Pavel Labath5eb721e2015-05-07 08:30:31 +00004720 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004721 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004722 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004723 }
4724}
4725
4726void
4727NativeProcessLinux::ResetForExec ()
4728{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004729 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004730 std::lock_guard<std::mutex> lock(m_event_mutex);
4731
Pavel Labath5eb721e2015-05-07 08:30:31 +00004732 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004733 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004734 log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004735 }
4736
4737 // Clear the pending notification if there was one.
4738 m_pending_notification_up.reset ();
4739
4740 // Clear the stop map - we no longer know anything about any thread state.
4741 // The caller is expected to reset thread states for all threads, and we
4742 // will assume anything we haven't heard about is running and requires a
4743 // stop.
4744 m_tid_map.clear ();
4745
Pavel Labath5eb721e2015-05-07 08:30:31 +00004746 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004747 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004748 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004749 }
4750}
Pavel Labathc0765592015-05-06 10:46:34 +00004751
4752bool
4753NativeProcessLinux::IsKnownThread (lldb::tid_t tid) const
4754{
4755 return m_tid_map.find (tid) != m_tid_map.end ();
4756}