blob: 4e4bbd8eb29e2c25b64504892f856b2026b36e7f [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/types.h>
62#include <sys/uio.h>
63#include <sys/user.h>
64#include <sys/wait.h>
65
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000066#if defined (__arm64__) || defined (__aarch64__)
67// NT_PRSTATUS and NT_FPREGSET definition
68#include <elf.h>
69#endif
70
Todd Fialacacde7d2014-09-27 16:54:22 +000071#ifdef __ANDROID__
72#define __ptrace_request int
73#define PT_DETACH PTRACE_DETACH
74#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000075
76#define DEBUG_PTRACE_MAXBYTES 20
77
78// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000079#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000080#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000081 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000082#endif
Todd Fialadda61942014-07-02 21:34:04 +000083#endif
84#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000085#ifndef PTRACE_SETREGS
86 #define PTRACE_SETREGS 13
87#endif
Todd Fialadda61942014-07-02 21:34:04 +000088#endif
89#ifndef PT_GETFPREGS
90#ifndef PTRACE_GETFPREGS
91 #define PTRACE_GETFPREGS 14
92#endif
93#endif
94#ifndef PT_SETFPREGS
95#ifndef PTRACE_SETFPREGS
96 #define PTRACE_SETFPREGS 15
97#endif
98#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000099#ifndef PTRACE_GETREGSET
100 #define PTRACE_GETREGSET 0x4204
101#endif
102#ifndef PTRACE_SETREGSET
103 #define PTRACE_SETREGSET 0x4205
104#endif
105#ifndef PTRACE_GET_THREAD_AREA
106 #define PTRACE_GET_THREAD_AREA 25
107#endif
108#ifndef PTRACE_ARCH_PRCTL
109 #define PTRACE_ARCH_PRCTL 30
110#endif
111#ifndef ARCH_GET_FS
112 #define ARCH_SET_GS 0x1001
113 #define ARCH_SET_FS 0x1002
114 #define ARCH_GET_FS 0x1003
115 #define ARCH_GET_GS 0x1004
116#endif
117
Todd Fiala0bce1b62014-08-17 00:10:50 +0000118#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000119
120// Support hardware breakpoints in case it has not been defined
121#ifndef TRAP_HWBKPT
122 #define TRAP_HWBKPT 4
123#endif
124
Todd Fialaaf245d12014-06-30 21:05:18 +0000125// We disable the tracing of ptrace calls for integration builds to
126// avoid the additional indirection and checks.
127#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000128#define PTRACE(req, pid, addr, data, data_size, error) \
129 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000130#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000131#define PTRACE(req, pid, addr, data, data_size, error) \
132 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000133#endif
134
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000135using namespace lldb;
136using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000137using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000138using namespace llvm;
139
Todd Fialaaf245d12014-06-30 21:05:18 +0000140// Private bits we only need internally.
141namespace
142{
Todd Fialaaf245d12014-06-30 21:05:18 +0000143 const UnixSignals&
144 GetUnixSignals ()
145 {
146 static process_linux::LinuxSignals signals;
147 return signals;
148 }
149
Todd Fialaaf245d12014-06-30 21:05:18 +0000150 Error
151 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
152 {
153 // Grab process info for the running process.
154 ProcessInstanceInfo process_info;
155 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000156 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000157
158 // Resolve the executable module.
159 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000160 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000161 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
162 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000163 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000164 exe_module_sp,
165 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
166
167 if (!error.Success ())
168 return error;
169
170 // Check if we've got our architecture from the exe_module.
171 arch = exe_module_sp->GetArchitecture ();
172 if (arch.IsValid ())
173 return Error();
174 else
175 return Error("failed to retrieve a valid architecture from the exe module");
176 }
177
178 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000179 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000180 {
181 uint8_t *ptr = (uint8_t *)bytes;
182 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
183 for(uint32_t i=0; i<loop_count; i++)
184 {
185 s.Printf ("[%x]", *ptr);
186 ptr++;
187 }
188 }
189
190 void
191 PtraceDisplayBytes(int &req, void *data, size_t data_size)
192 {
193 StreamString buf;
194 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
195 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
196
197 if (verbose_log)
198 {
199 switch(req)
200 {
201 case PTRACE_POKETEXT:
202 {
203 DisplayBytes(buf, &data, 8);
204 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
205 break;
206 }
207 case PTRACE_POKEDATA:
208 {
209 DisplayBytes(buf, &data, 8);
210 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
211 break;
212 }
213 case PTRACE_POKEUSER:
214 {
215 DisplayBytes(buf, &data, 8);
216 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
217 break;
218 }
219 case PTRACE_SETREGS:
220 {
221 DisplayBytes(buf, data, data_size);
222 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
223 break;
224 }
225 case PTRACE_SETFPREGS:
226 {
227 DisplayBytes(buf, data, data_size);
228 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
229 break;
230 }
231 case PTRACE_SETSIGINFO:
232 {
233 DisplayBytes(buf, data, sizeof(siginfo_t));
234 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
235 break;
236 }
237 case PTRACE_SETREGSET:
238 {
239 // Extract iov_base from data, which is a pointer to the struct IOVEC
240 DisplayBytes(buf, *(void **)data, data_size);
241 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
242 break;
243 }
244 default:
245 {
246 }
247 }
248 }
249 }
250
251 // Wrapper for ptrace to catch errors and log calls.
252 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
253 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000254 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
255 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000256 {
257 long int result;
258
259 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
260
261 PtraceDisplayBytes(req, data, data_size);
262
Chaoren Lin97ccc292015-02-03 01:51:12 +0000263 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000264 errno = 0;
265 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000266 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000267 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000268 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000269
Chaoren Lin97ccc292015-02-03 01:51:12 +0000270 if (result == -1)
271 error.SetErrorToErrno();
272
Todd Fialaaf245d12014-06-30 21:05:18 +0000273 if (log)
274 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
275 reqName, pid, addr, data, data_size, result, file, line);
276
277 PtraceDisplayBytes(req, data, data_size);
278
Chaoren Lin97ccc292015-02-03 01:51:12 +0000279 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000280 {
281 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000282 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000283 {
284 case ESRCH: str = "ESRCH"; break;
285 case EINVAL: str = "EINVAL"; break;
286 case EBUSY: str = "EBUSY"; break;
287 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000288 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000289 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000290 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000291 }
292
293 return result;
294 }
295
296#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
297 // Wrapper for ptrace when logging is not required.
298 // Sets errno to 0 prior to calling ptrace.
299 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000300 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000301 {
302 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000303
304 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000305 errno = 0;
306 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000307 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000308 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000309 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000310
311 if (result == -1)
312 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000313 return result;
314 }
315#endif
316
317 //------------------------------------------------------------------------------
318 // Static implementations of NativeProcessLinux::ReadMemory and
319 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
320 // functions without needed to go thru the thread funnel.
321
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000322 size_t
323 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000324 lldb::pid_t pid,
325 lldb::addr_t vm_addr,
326 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000327 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000328 Error &error)
329 {
330 // ptrace word size is determined by the host, not the child
331 static const unsigned word_size = sizeof(void*);
332 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000333 size_t bytes_read;
334 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000335 long data;
336
337 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
338 if (log)
339 ProcessPOSIXLog::IncNestLevel();
340 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
341 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
342 pid, word_size, (void*)vm_addr, buf, size);
343
344 assert(sizeof(data) >= word_size);
345 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
346 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000347 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
348 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000349 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000350 if (log)
351 ProcessPOSIXLog::DecNestLevel();
352 return bytes_read;
353 }
354
355 remainder = size - bytes_read;
356 remainder = remainder > word_size ? word_size : remainder;
357
358 // Copy the data into our buffer
359 for (unsigned i = 0; i < remainder; ++i)
360 dst[i] = ((data >> i*8) & 0xFF);
361
362 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
363 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
364 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
365 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
366 {
367 uintptr_t print_dst = 0;
368 // Format bytes from data by moving into print_dst for log output
369 for (unsigned i = 0; i < remainder; ++i)
370 print_dst |= (((data >> i*8) & 0xFF) << i*8);
371 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
372 (void*)vm_addr, print_dst, (unsigned long)data);
373 }
374
375 vm_addr += word_size;
376 dst += word_size;
377 }
378
379 if (log)
380 ProcessPOSIXLog::DecNestLevel();
381 return bytes_read;
382 }
383
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000384 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000385 DoWriteMemory(
386 lldb::pid_t pid,
387 lldb::addr_t vm_addr,
388 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000389 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000390 Error &error)
391 {
392 // ptrace word size is determined by the host, not the child
393 static const unsigned word_size = sizeof(void*);
394 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000395 size_t bytes_written = 0;
396 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000397
398 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
399 if (log)
400 ProcessPOSIXLog::IncNestLevel();
401 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
402 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
403 pid, word_size, (void*)vm_addr, buf, size);
404
405 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
406 {
407 remainder = size - bytes_written;
408 remainder = remainder > word_size ? word_size : remainder;
409
410 if (remainder == word_size)
411 {
412 unsigned long data = 0;
413 assert(sizeof(data) >= word_size);
414 for (unsigned i = 0; i < word_size; ++i)
415 data |= (unsigned long)src[i] << i*8;
416
417 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
418 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
419 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
420 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
421 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000422 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000423
Chaoren Lin97ccc292015-02-03 01:51:12 +0000424 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000425 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000426 if (log)
427 ProcessPOSIXLog::DecNestLevel();
428 return bytes_written;
429 }
430 }
431 else
432 {
433 unsigned char buff[8];
434 if (DoReadMemory(pid, vm_addr,
435 buff, word_size, error) != word_size)
436 {
437 if (log)
438 ProcessPOSIXLog::DecNestLevel();
439 return bytes_written;
440 }
441
442 memcpy(buff, src, remainder);
443
444 if (DoWriteMemory(pid, vm_addr,
445 buff, word_size, error) != word_size)
446 {
447 if (log)
448 ProcessPOSIXLog::DecNestLevel();
449 return bytes_written;
450 }
451
452 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
453 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
454 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
455 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
456 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000457 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000458 }
459
460 vm_addr += word_size;
461 src += word_size;
462 }
463 if (log)
464 ProcessPOSIXLog::DecNestLevel();
465 return bytes_written;
466 }
467
468 //------------------------------------------------------------------------------
469 /// @class Operation
470 /// @brief Represents a NativeProcessLinux operation.
471 ///
472 /// Under Linux, it is not possible to ptrace() from any other thread but the
473 /// one that spawned or attached to the process from the start. Therefore, when
474 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
475 /// process the operation must be "funneled" to a specific thread to perform the
476 /// task. The Operation class provides an abstract base for all services the
477 /// NativeProcessLinux must perform via the single virtual function Execute, thus
478 /// encapsulating the code that needs to run in the privileged context.
479 class Operation
480 {
481 public:
482 Operation () : m_error() { }
483
484 virtual
485 ~Operation() {}
486
487 virtual void
488 Execute (NativeProcessLinux *process) = 0;
489
490 const Error &
491 GetError () const { return m_error; }
492
493 protected:
494 Error m_error;
495 };
496
497 //------------------------------------------------------------------------------
498 /// @class ReadOperation
499 /// @brief Implements NativeProcessLinux::ReadMemory.
500 class ReadOperation : public Operation
501 {
502 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000503 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000504 lldb::addr_t addr,
505 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000506 size_t size,
507 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000508 Operation (),
509 m_addr (addr),
510 m_buff (buff),
511 m_size (size),
512 m_result (result)
513 {
514 }
515
516 void Execute (NativeProcessLinux *process) override;
517
518 private:
519 lldb::addr_t m_addr;
520 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000521 size_t m_size;
522 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000523 };
524
525 void
526 ReadOperation::Execute (NativeProcessLinux *process)
527 {
528 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
529 }
530
531 //------------------------------------------------------------------------------
532 /// @class WriteOperation
533 /// @brief Implements NativeProcessLinux::WriteMemory.
534 class WriteOperation : public Operation
535 {
536 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000537 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000538 lldb::addr_t addr,
539 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000540 size_t size,
541 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000542 Operation (),
543 m_addr (addr),
544 m_buff (buff),
545 m_size (size),
546 m_result (result)
547 {
548 }
549
550 void Execute (NativeProcessLinux *process) override;
551
552 private:
553 lldb::addr_t m_addr;
554 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000555 size_t m_size;
556 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000557 };
558
559 void
560 WriteOperation::Execute(NativeProcessLinux *process)
561 {
562 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
563 }
564
565 //------------------------------------------------------------------------------
566 /// @class ReadRegOperation
567 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
568 class ReadRegOperation : public Operation
569 {
570 public:
571 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000572 RegisterValue &value)
573 : m_tid(tid),
574 m_offset(static_cast<uintptr_t> (offset)),
575 m_reg_name(reg_name),
576 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000577 { }
578
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000579 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000580
581 private:
582 lldb::tid_t m_tid;
583 uintptr_t m_offset;
584 const char *m_reg_name;
585 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000586 };
587
588 void
589 ReadRegOperation::Execute(NativeProcessLinux *monitor)
590 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000591#if defined (__arm64__) || defined (__aarch64__)
592 if (m_offset > sizeof(struct user_pt_regs))
593 {
594 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
595 if (offset > sizeof(struct user_fpsimd_state))
596 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000597 m_error.SetErrorString("invalid offset value");
598 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000599 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000600 elf_fpregset_t regs;
601 int regset = NT_FPREGSET;
602 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000603
Chaoren Lin97ccc292015-02-03 01:51:12 +0000604 ioVec.iov_base = &regs;
605 ioVec.iov_len = sizeof regs;
606 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
607 if (m_error.Success())
608 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000609 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000610 if (monitor->GetArchitecture(arch))
611 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000612 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000613 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000614 }
615 }
616 else
617 {
618 elf_gregset_t regs;
619 int regset = NT_PRSTATUS;
620 struct iovec ioVec;
621
622 ioVec.iov_base = &regs;
623 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000624 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
625 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000626 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000627 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000628 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000629 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 else
631 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000632 }
633 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000634#elif defined (__mips__)
635 elf_gregset_t regs;
636 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
637 if (m_error.Success())
638 {
639 lldb_private::ArchSpec arch;
640 if (monitor->GetArchitecture(arch))
641 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
642 else
643 m_error.SetErrorString("failed to get architecture");
644 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000645#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000646 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
647
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000648 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 +0000649 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000650 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000651
Todd Fialaaf245d12014-06-30 21:05:18 +0000652 if (log)
653 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
654 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000655#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000656 }
657
658 //------------------------------------------------------------------------------
659 /// @class WriteRegOperation
660 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
661 class WriteRegOperation : public Operation
662 {
663 public:
664 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000665 const RegisterValue &value)
666 : m_tid(tid),
667 m_offset(offset),
668 m_reg_name(reg_name),
669 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000670 { }
671
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000672 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000673
674 private:
675 lldb::tid_t m_tid;
676 uintptr_t m_offset;
677 const char *m_reg_name;
678 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000679 };
680
681 void
682 WriteRegOperation::Execute(NativeProcessLinux *monitor)
683 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000684#if defined (__arm64__) || defined (__aarch64__)
685 if (m_offset > sizeof(struct user_pt_regs))
686 {
687 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
688 if (offset > sizeof(struct user_fpsimd_state))
689 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000690 m_error.SetErrorString("invalid offset value");
691 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000692 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000693 elf_fpregset_t regs;
694 int regset = NT_FPREGSET;
695 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000696
Chaoren Lin97ccc292015-02-03 01:51:12 +0000697 ioVec.iov_base = &regs;
698 ioVec.iov_len = sizeof regs;
699 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000700 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000701 {
702 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
703 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000704 }
705 }
706 else
707 {
708 elf_gregset_t regs;
709 int regset = NT_PRSTATUS;
710 struct iovec ioVec;
711
712 ioVec.iov_base = &regs;
713 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000714 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000715 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000716 {
717 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000718 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000719 }
720 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000721#elif defined (__mips__)
722 elf_gregset_t regs;
723 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
724 if (m_error.Success())
725 {
726 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
727 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
728 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000729#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000730 void* buf;
731 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
732
733 buf = (void*) m_value.GetAsUInt64();
734
735 if (log)
736 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000737 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000738#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000739 }
740
741 //------------------------------------------------------------------------------
742 /// @class ReadGPROperation
743 /// @brief Implements NativeProcessLinux::ReadGPR.
744 class ReadGPROperation : public Operation
745 {
746 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000747 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
748 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000749 { }
750
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000751 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000752
753 private:
754 lldb::tid_t m_tid;
755 void *m_buf;
756 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000757 };
758
759 void
760 ReadGPROperation::Execute(NativeProcessLinux *monitor)
761 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000762#if defined (__arm64__) || defined (__aarch64__)
763 int regset = NT_PRSTATUS;
764 struct iovec ioVec;
765
766 ioVec.iov_base = m_buf;
767 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000768 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000769#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000770 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000771#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000772 }
773
774 //------------------------------------------------------------------------------
775 /// @class ReadFPROperation
776 /// @brief Implements NativeProcessLinux::ReadFPR.
777 class ReadFPROperation : public Operation
778 {
779 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000780 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
781 : m_tid(tid),
782 m_buf(buf),
783 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000784 { }
785
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000786 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000787
788 private:
789 lldb::tid_t m_tid;
790 void *m_buf;
791 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000792 };
793
794 void
795 ReadFPROperation::Execute(NativeProcessLinux *monitor)
796 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000797#if defined (__arm64__) || defined (__aarch64__)
798 int regset = NT_FPREGSET;
799 struct iovec ioVec;
800
801 ioVec.iov_base = m_buf;
802 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000803 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000804#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000805 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000806#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000807 }
808
809 //------------------------------------------------------------------------------
810 /// @class ReadRegisterSetOperation
811 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
812 class ReadRegisterSetOperation : public Operation
813 {
814 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000815 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
816 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000817 { }
818
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000819 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000820
821 private:
822 lldb::tid_t m_tid;
823 void *m_buf;
824 size_t m_buf_size;
825 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000826 };
827
828 void
829 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
830 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000831 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000832 }
833
834 //------------------------------------------------------------------------------
835 /// @class WriteGPROperation
836 /// @brief Implements NativeProcessLinux::WriteGPR.
837 class WriteGPROperation : public Operation
838 {
839 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000840 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
841 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000842 { }
843
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000844 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000845
846 private:
847 lldb::tid_t m_tid;
848 void *m_buf;
849 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000850 };
851
852 void
853 WriteGPROperation::Execute(NativeProcessLinux *monitor)
854 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000855#if defined (__arm64__) || defined (__aarch64__)
856 int regset = NT_PRSTATUS;
857 struct iovec ioVec;
858
859 ioVec.iov_base = m_buf;
860 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000861 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000862#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000863 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000864#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000865 }
866
867 //------------------------------------------------------------------------------
868 /// @class WriteFPROperation
869 /// @brief Implements NativeProcessLinux::WriteFPR.
870 class WriteFPROperation : public Operation
871 {
872 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000873 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
874 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000875 { }
876
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000877 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000878
879 private:
880 lldb::tid_t m_tid;
881 void *m_buf;
882 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000883 };
884
885 void
886 WriteFPROperation::Execute(NativeProcessLinux *monitor)
887 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000888#if defined (__arm64__) || defined (__aarch64__)
889 int regset = NT_FPREGSET;
890 struct iovec ioVec;
891
892 ioVec.iov_base = m_buf;
893 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000894 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000895#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000896 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000897#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000898 }
899
900 //------------------------------------------------------------------------------
901 /// @class WriteRegisterSetOperation
902 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
903 class WriteRegisterSetOperation : public Operation
904 {
905 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000906 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
907 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000908 { }
909
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000910 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000911
912 private:
913 lldb::tid_t m_tid;
914 void *m_buf;
915 size_t m_buf_size;
916 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000917 };
918
919 void
920 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
921 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000922 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000923 }
924
925 //------------------------------------------------------------------------------
926 /// @class ResumeOperation
927 /// @brief Implements NativeProcessLinux::Resume.
928 class ResumeOperation : public Operation
929 {
930 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000931 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
932 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000933
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000934 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000935
936 private:
937 lldb::tid_t m_tid;
938 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000939 };
940
941 void
942 ResumeOperation::Execute(NativeProcessLinux *monitor)
943 {
944 intptr_t data = 0;
945
946 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
947 data = m_signo;
948
Chaoren Lin97ccc292015-02-03 01:51:12 +0000949 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
950 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000951 {
952 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
953
954 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000955 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000956 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000957 }
958
959 //------------------------------------------------------------------------------
960 /// @class SingleStepOperation
961 /// @brief Implements NativeProcessLinux::SingleStep.
962 class SingleStepOperation : public Operation
963 {
964 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000965 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
966 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000967
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000968 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000969
970 private:
971 lldb::tid_t m_tid;
972 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000973 };
974
975 void
976 SingleStepOperation::Execute(NativeProcessLinux *monitor)
977 {
978 intptr_t data = 0;
979
980 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
981 data = m_signo;
982
Chaoren Lin97ccc292015-02-03 01:51:12 +0000983 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000984 }
985
986 //------------------------------------------------------------------------------
987 /// @class SiginfoOperation
988 /// @brief Implements NativeProcessLinux::GetSignalInfo.
989 class SiginfoOperation : public Operation
990 {
991 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000992 SiginfoOperation(lldb::tid_t tid, void *info)
993 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000994
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000995 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000996
997 private:
998 lldb::tid_t m_tid;
999 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001000 };
1001
1002 void
1003 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1004 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001005 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001006 }
1007
1008 //------------------------------------------------------------------------------
1009 /// @class EventMessageOperation
1010 /// @brief Implements NativeProcessLinux::GetEventMessage.
1011 class EventMessageOperation : public Operation
1012 {
1013 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001014 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1015 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001016
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001017 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001018
1019 private:
1020 lldb::tid_t m_tid;
1021 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001022 };
1023
1024 void
1025 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1026 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001027 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001028 }
1029
1030 class DetachOperation : public Operation
1031 {
1032 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001033 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001034
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001035 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001036
1037 private:
1038 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001039 };
1040
1041 void
1042 DetachOperation::Execute(NativeProcessLinux *monitor)
1043 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001044 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001045 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001046} // end of anonymous namespace
1047
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001048// Simple helper function to ensure flags are enabled on the given file
1049// descriptor.
1050static Error
1051EnsureFDFlags(int fd, int flags)
1052{
1053 Error error;
1054
1055 int status = fcntl(fd, F_GETFL);
1056 if (status == -1)
1057 {
1058 error.SetErrorToErrno();
1059 return error;
1060 }
1061
1062 if (fcntl(fd, F_SETFL, status | flags) == -1)
1063 {
1064 error.SetErrorToErrno();
1065 return error;
1066 }
1067
1068 return error;
1069}
1070
1071// This class encapsulates the privileged thread which performs all ptrace and wait operations on
1072// the inferior. The thread consists of a main loop which waits for events and processes them
1073// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1074// the inferior process. Upon receiving this signal we do a waitpid to get more information
1075// and dispatch to NativeProcessLinux::MonitorCallback.
1076// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1077// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1078// pipe, and the completion of the operation is signalled over the semaphore.
1079// - thread exit event: this is signaled from the Monitor destructor by closing the write end
1080// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001081class NativeProcessLinux::Monitor
1082{
Pavel Labath1107b5a2015-04-17 14:07:49 +00001083private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001084 // The initial monitor operation (launch or attach). It returns a inferior process id.
1085 std::unique_ptr<InitialOperation> m_initial_operation_up;
1086
1087 ::pid_t m_child_pid = -1;
1088 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001089
1090 enum { READ, WRITE };
1091 int m_pipefd[2] = {-1, -1};
1092 int m_signal_fd = -1;
1093 HostThread m_thread;
1094
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001095 // current operation which must be executed on the priviliged thread
1096 Mutex m_operation_mutex;
1097 Operation *m_operation = nullptr;
1098 sem_t m_operation_sem;
1099 Error m_operation_error;
1100
Pavel Labath45f5cb32015-05-05 15:05:50 +00001101 unsigned m_operation_nesting_level = 0;
1102
1103 static constexpr char operation_command = 'o';
1104 static constexpr char begin_block_command = '{';
1105 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001106
Pavel Labath1107b5a2015-04-17 14:07:49 +00001107 void
1108 HandleSignals();
1109
1110 void
1111 HandleWait();
1112
1113 // Returns true if the thread should exit.
1114 bool
1115 HandleCommands();
1116
1117 void
1118 MainLoop();
1119
1120 static void *
1121 RunMonitor(void *arg);
1122
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001123 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001124 WaitForAck();
1125
1126 void
1127 BeginOperationBlock()
1128 {
1129 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
1130 WaitForAck();
1131 }
1132
1133 void
1134 EndOperationBlock()
1135 {
1136 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
1137 WaitForAck();
1138 }
1139
Pavel Labath1107b5a2015-04-17 14:07:49 +00001140public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001141 Monitor(const InitialOperation &initial_operation,
1142 NativeProcessLinux *native_process)
1143 : m_initial_operation_up(new InitialOperation(initial_operation)),
1144 m_native_process(native_process)
1145 {
1146 sem_init(&m_operation_sem, 0, 0);
1147 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001148
1149 ~Monitor();
1150
1151 Error
1152 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001153
1154 void
Pavel Labath45f5cb32015-05-05 15:05:50 +00001155 Terminate();
1156
1157 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001158 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001159
1160 class ScopedOperationLock {
1161 Monitor &m_monitor;
1162
1163 public:
1164 ScopedOperationLock(Monitor &monitor)
1165 : m_monitor(monitor)
1166 { m_monitor.BeginOperationBlock(); }
1167
1168 ~ScopedOperationLock()
1169 { m_monitor.EndOperationBlock(); }
1170 };
Pavel Labath1107b5a2015-04-17 14:07:49 +00001171};
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001172constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +00001173constexpr char NativeProcessLinux::Monitor::begin_block_command;
1174constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001175
1176Error
1177NativeProcessLinux::Monitor::Initialize()
1178{
1179 Error error;
1180
1181 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1182 // listening for these signals over a signalfd file descriptors. This allows us to wait for
1183 // multiple kinds of events with select.
1184 sigset_t signals;
1185 sigemptyset(&signals);
1186 sigaddset(&signals, SIGCHLD);
1187 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1188 if (m_signal_fd < 0)
1189 {
1190 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1191 __FUNCTION__, strerror(errno));
1192
1193 }
1194
1195 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1196 {
1197 error.SetErrorToErrno();
1198 return error;
1199 }
1200
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001201 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1202 return error;
1203 }
1204
1205 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1206 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001207 if (!m_thread.IsJoinable())
1208 return Error("Failed to create monitor thread for NativeProcessLinux.");
1209
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001210 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001211 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001212}
1213
1214void
1215NativeProcessLinux::Monitor::DoOperation(Operation *op)
1216{
1217 if (m_thread.EqualsThread(pthread_self())) {
1218 // If we're on the Monitor thread, we can simply execute the operation.
1219 op->Execute(m_native_process);
1220 return;
1221 }
1222
1223 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1224 Mutex::Locker lock(m_operation_mutex);
1225
1226 m_operation = op;
1227
1228 // notify the thread that an operation is ready to be processed
1229 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1230
Pavel Labath45f5cb32015-05-05 15:05:50 +00001231 WaitForAck();
1232}
1233
1234void
1235NativeProcessLinux::Monitor::Terminate()
1236{
1237 if (m_pipefd[WRITE] >= 0)
1238 {
1239 close(m_pipefd[WRITE]);
1240 m_pipefd[WRITE] = -1;
1241 }
1242 if (m_thread.IsJoinable())
1243 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00001244}
1245
Pavel Labath1107b5a2015-04-17 14:07:49 +00001246NativeProcessLinux::Monitor::~Monitor()
1247{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001248 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +00001249 if (m_pipefd[READ] >= 0)
1250 close(m_pipefd[READ]);
1251 if (m_signal_fd >= 0)
1252 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001253 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001254}
1255
1256void
1257NativeProcessLinux::Monitor::HandleSignals()
1258{
1259 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1260
1261 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1262 // all the information from waitpid(). We just need to read all the signals so that we can
1263 // sleep next time we reach select().
1264 while (true)
1265 {
1266 signalfd_siginfo info;
1267 ssize_t size = read(m_signal_fd, &info, sizeof info);
1268 if (size == -1)
1269 {
1270 if (errno == EAGAIN || errno == EWOULDBLOCK)
1271 break; // We are done.
1272 if (errno == EINTR)
1273 continue;
1274 if (log)
1275 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1276 __FUNCTION__, strerror(errno));
1277 break;
1278 }
1279 if (size != sizeof info)
1280 {
1281 // We got incomplete information structure. This should not happen, let's just log
1282 // that.
1283 if (log)
1284 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1285 "structure size is %zd, read returned %zd bytes",
1286 __FUNCTION__, sizeof info, size);
1287 break;
1288 }
1289 if (log)
1290 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1291 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1292 }
1293}
1294
1295void
1296NativeProcessLinux::Monitor::HandleWait()
1297{
1298 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1299 // Process all pending waitpid notifications.
1300 while (true)
1301 {
1302 int status = -1;
1303 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1304
1305 if (wait_pid == 0)
1306 break; // We are done.
1307
1308 if (wait_pid == -1)
1309 {
1310 if (errno == EINTR)
1311 continue;
1312
1313 if (log)
1314 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1315 __FUNCTION__, m_child_pid, strerror(errno));
1316 break;
1317 }
1318
1319 bool exited = false;
1320 int signal = 0;
1321 int exit_status = 0;
1322 const char *status_cstr = NULL;
1323 if (WIFSTOPPED(status))
1324 {
1325 signal = WSTOPSIG(status);
1326 status_cstr = "STOPPED";
1327 }
1328 else if (WIFEXITED(status))
1329 {
1330 exit_status = WEXITSTATUS(status);
1331 status_cstr = "EXITED";
1332 exited = true;
1333 }
1334 else if (WIFSIGNALED(status))
1335 {
1336 signal = WTERMSIG(status);
1337 status_cstr = "SIGNALED";
1338 if (wait_pid == abs(m_child_pid)) {
1339 exited = true;
1340 exit_status = -1;
1341 }
1342 }
1343 else
1344 status_cstr = "(\?\?\?)";
1345
1346 if (log)
1347 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1348 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1349 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1350
1351 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1352 }
1353}
1354
1355bool
1356NativeProcessLinux::Monitor::HandleCommands()
1357{
1358 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1359
1360 while (true)
1361 {
1362 char command = 0;
1363 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1364 if (size == -1)
1365 {
1366 if (errno == EAGAIN || errno == EWOULDBLOCK)
1367 return false;
1368 if (errno == EINTR)
1369 continue;
1370 if (log)
1371 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1372 return true;
1373 }
1374 if (size == 0) // end of file - write end closed
1375 {
1376 if (log)
1377 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001378 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +00001379 return true; // We are done.
1380 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001381
1382 switch (command)
1383 {
1384 case operation_command:
1385 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001386 break;
1387 case begin_block_command:
1388 ++m_operation_nesting_level;
1389 break;
1390 case end_block_command:
1391 assert(m_operation_nesting_level > 0);
1392 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001393 break;
1394 default:
1395 if (log)
1396 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1397 __FUNCTION__, command);
1398 }
Pavel Labath45f5cb32015-05-05 15:05:50 +00001399
1400 // notify calling thread that the command has been processed
1401 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001402 }
1403}
1404
1405void
1406NativeProcessLinux::Monitor::MainLoop()
1407{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001408 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1409 m_initial_operation_up.reset();
1410 m_child_pid = -getpgid(child_pid),
1411 sem_post(&m_operation_sem);
1412
Pavel Labath1107b5a2015-04-17 14:07:49 +00001413 while (true)
1414 {
1415 fd_set fds;
1416 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001417 // Only process waitpid events if we are outside of an operation block. Any pending
1418 // events will be processed after we leave the block.
1419 if (m_operation_nesting_level == 0)
1420 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001421 FD_SET(m_pipefd[READ], &fds);
1422
1423 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1424 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1425 if (r < 0)
1426 {
1427 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1428 if (log)
1429 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1430 __FUNCTION__, strerror(errno));
1431 return;
1432 }
1433
1434 if (FD_ISSET(m_pipefd[READ], &fds))
1435 {
1436 if (HandleCommands())
1437 return;
1438 }
1439
1440 if (FD_ISSET(m_signal_fd, &fds))
1441 {
1442 HandleSignals();
1443 HandleWait();
1444 }
1445 }
1446}
1447
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001448Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001449NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001450{
1451 Error error;
1452 while (sem_wait(&m_operation_sem) != 0)
1453 {
1454 if (errno == EINTR)
1455 continue;
1456
1457 error.SetErrorToErrno();
1458 return error;
1459 }
1460
1461 return m_operation_error;
1462}
1463
Pavel Labath1107b5a2015-04-17 14:07:49 +00001464void *
1465NativeProcessLinux::Monitor::RunMonitor(void *arg)
1466{
1467 static_cast<Monitor *>(arg)->MainLoop();
1468 return nullptr;
1469}
1470
1471
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001472NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001473 char const **argv,
1474 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001475 const std::string &stdin_path,
1476 const std::string &stdout_path,
1477 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001478 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001479 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001480 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +00001481 m_argv(argv),
1482 m_envp(envp),
1483 m_stdin_path(stdin_path),
1484 m_stdout_path(stdout_path),
1485 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001486 m_working_dir(working_dir),
1487 m_launch_info(launch_info)
1488{
1489}
Todd Fialaaf245d12014-06-30 21:05:18 +00001490
1491NativeProcessLinux::LaunchArgs::~LaunchArgs()
1492{ }
1493
Todd Fialaaf245d12014-06-30 21:05:18 +00001494// -----------------------------------------------------------------------------
1495// Public Static Methods
1496// -----------------------------------------------------------------------------
1497
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001498Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001499NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001500 Module *exe_module,
1501 ProcessLaunchInfo &launch_info,
1502 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001503 NativeProcessProtocolSP &native_process_sp)
1504{
1505 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1506
1507 Error error;
1508
1509 // Verify the working directory is valid if one was specified.
1510 const char* working_dir = launch_info.GetWorkingDirectory ();
1511 if (working_dir)
1512 {
1513 FileSpec working_dir_fs (working_dir, true);
1514 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1515 {
1516 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1517 return error;
1518 }
1519 }
1520
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001521 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001522
1523 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001524 std::string stdin_path;
1525 std::string stdout_path;
1526 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001527
1528 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001529 if (file_action)
1530 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001531
1532 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001533 if (file_action)
1534 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001535
1536 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001537 if (file_action)
1538 stderr_path = file_action->GetPath ();
1539
1540 if (log)
1541 {
1542 if (!stdin_path.empty ())
1543 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1544 else
1545 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1546
1547 if (!stdout_path.empty ())
1548 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1549 else
1550 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1551
1552 if (!stderr_path.empty ())
1553 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1554 else
1555 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1556 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001557
1558 // Create the NativeProcessLinux in launch mode.
1559 native_process_sp.reset (new NativeProcessLinux ());
1560
1561 if (log)
1562 {
1563 int i = 0;
1564 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1565 {
1566 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1567 ++i;
1568 }
1569 }
1570
1571 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1572 {
1573 native_process_sp.reset ();
1574 error.SetErrorStringWithFormat ("failed to register the native delegate");
1575 return error;
1576 }
1577
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001578 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001579 exe_module,
1580 launch_info.GetArguments ().GetConstArgumentVector (),
1581 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1582 stdin_path,
1583 stdout_path,
1584 stderr_path,
1585 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001586 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001587 error);
1588
1589 if (error.Fail ())
1590 {
1591 native_process_sp.reset ();
1592 if (log)
1593 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1594 return error;
1595 }
1596
1597 launch_info.SetProcessID (native_process_sp->GetID ());
1598
1599 return error;
1600}
1601
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001602Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001603NativeProcessLinux::AttachToProcess (
1604 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001605 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001606 NativeProcessProtocolSP &native_process_sp)
1607{
1608 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1609 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1610 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1611
1612 // Grab the current platform architecture. This should be Linux,
1613 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001614 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001615 if (!platform_sp)
1616 return Error("failed to get a valid default platform");
1617
1618 // Retrieve the architecture for the running process.
1619 ArchSpec process_arch;
1620 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1621 if (!error.Success ())
1622 return error;
1623
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001624 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001625
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001626 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001627 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001628 error.SetErrorStringWithFormat ("failed to register the native delegate");
1629 return error;
1630 }
1631
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001632 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001633 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001634 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001635
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001636 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001637 return error;
1638}
1639
1640// -----------------------------------------------------------------------------
1641// Public Instance Methods
1642// -----------------------------------------------------------------------------
1643
1644NativeProcessLinux::NativeProcessLinux () :
1645 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1646 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001647 m_supports_mem_region (eLazyBoolCalculate),
1648 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001649 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001650{
1651}
1652
1653//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001654// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1655// Refer to Monitor and Operation classes to see why this is necessary.
1656//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001657void
1658NativeProcessLinux::LaunchInferior (
1659 Module *module,
1660 const char *argv[],
1661 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001662 const std::string &stdin_path,
1663 const std::string &stdout_path,
1664 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001665 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001666 const ProcessLaunchInfo &launch_info,
1667 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001668{
1669 if (module)
1670 m_arch = module->GetArchitecture ();
1671
Chaoren Linfa03ad22015-02-03 01:50:42 +00001672 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001673
1674 std::unique_ptr<LaunchArgs> args(
1675 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001676 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001677 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001678 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001679
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001680 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001681 if (!error.Success ())
1682 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001683}
1684
1685void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001686NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001687{
1688 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1689 if (log)
1690 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1691
1692 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001693 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 if (!platform_sp)
1695 {
1696 if (log)
1697 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1698 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001699 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001700 }
1701
1702 // Gather info about the process.
1703 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001704 if (!platform_sp->GetProcessInfo (pid, process_info))
1705 {
1706 if (log)
1707 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1708 error.SetErrorString ("failed to get process info");
1709 return;
1710 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001711
1712 // Resolve the executable module
1713 ModuleSP exe_module_sp;
1714 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001715 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001716 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001717 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001718 if (!error.Success())
1719 return;
1720
1721 // Set the architecture to the exe architecture.
1722 m_arch = exe_module_sp->GetArchitecture();
1723 if (log)
1724 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1725
1726 m_pid = pid;
1727 SetState(eStateAttaching);
1728
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001729 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 if (!error.Success ())
1731 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001732}
1733
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001734void
1735NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001736{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001737 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001738}
1739
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001740::pid_t
1741NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001742{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001743 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001744
1745 const char **argv = args->m_argv;
1746 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001747 const char *working_dir = args->m_working_dir;
1748
1749 lldb_utility::PseudoTerminal terminal;
1750 const size_t err_len = 1024;
1751 char err_str[err_len];
1752 lldb::pid_t pid;
1753 NativeThreadProtocolSP thread_sp;
1754
1755 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001756
1757 // Propagate the environment if one is not supplied.
1758 if (envp == NULL || envp[0] == NULL)
1759 envp = const_cast<const char **>(environ);
1760
1761 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1762 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001763 error.SetErrorToGenericError();
1764 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1765 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001766 }
1767
1768 // Recognized child exit status codes.
1769 enum {
1770 ePtraceFailed = 1,
1771 eDupStdinFailed,
1772 eDupStdoutFailed,
1773 eDupStderrFailed,
1774 eChdirFailed,
1775 eExecFailed,
1776 eSetGidFailed
1777 };
1778
1779 // Child process.
1780 if (pid == 0)
1781 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001782 // FIXME consider opening a pipe between parent/child and have this forked child
1783 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001784
Todd Fiala75f47c32014-10-11 21:42:09 +00001785 // Start tracing this child that is about to exec.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001786 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1787 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001788 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001789
Pavel Labath493c3a12015-02-04 10:36:57 +00001790 // terminal has already dupped the tty descriptors to stdin/out/err.
1791 // This closes original fd from which they were copied (and avoids
1792 // leaking descriptors to the debugged process.
1793 terminal.CloseSlaveFileDescriptor();
1794
Todd Fialaaf245d12014-06-30 21:05:18 +00001795 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001796 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001797 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001798
1799 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001800 if (setpgid(0, 0) != 0)
1801 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001802 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001803 // Don't allow this to prevent an inferior exec.
1804 }
1805
1806 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001807 if (!args->m_stdin_path.empty ())
1808 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001809 exit(eDupStdinFailed);
1810
Todd Fiala75f47c32014-10-11 21:42:09 +00001811 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001812 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001813 exit(eDupStdoutFailed);
1814
Todd Fiala75f47c32014-10-11 21:42:09 +00001815 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001816 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001817 exit(eDupStderrFailed);
1818
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001819 // Close everything besides stdin, stdout, and stderr that has no file
1820 // action to avoid leaking
1821 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1822 if (!args->m_launch_info.GetFileActionForFD(fd))
1823 close(fd);
1824
Todd Fialaaf245d12014-06-30 21:05:18 +00001825 // Change working directory
1826 if (working_dir != NULL && working_dir[0])
1827 if (0 != ::chdir(working_dir))
1828 exit(eChdirFailed);
1829
Todd Fiala0bce1b62014-08-17 00:10:50 +00001830 // Disable ASLR if requested.
1831 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1832 {
1833 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1834 if (old_personality == -1)
1835 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001836 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001837 }
1838 else
1839 {
1840 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1841 if (new_personality == -1)
1842 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001843 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001844 }
1845 else
1846 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001847 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001848 }
1849 }
1850 }
1851
Todd Fiala75f47c32014-10-11 21:42:09 +00001852 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001853 execve(argv[0],
1854 const_cast<char *const *>(argv),
1855 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001856
1857 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001858 exit(eExecFailed);
1859 }
1860
Todd Fiala75f47c32014-10-11 21:42:09 +00001861 //
1862 // This is the parent code here.
1863 //
1864 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1865
Todd Fialaaf245d12014-06-30 21:05:18 +00001866 // Wait for the child process to trap on its call to execve.
1867 ::pid_t wpid;
1868 int status;
1869 if ((wpid = waitpid(pid, &status, 0)) < 0)
1870 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001871 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001872 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001873 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1874 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001875
1876 // Mark the inferior as invalid.
1877 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001878 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001879
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001880 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001881 }
1882 else if (WIFEXITED(status))
1883 {
1884 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001885 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001886 switch (WEXITSTATUS(status))
1887 {
1888 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001889 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001890 break;
1891 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001892 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001893 break;
1894 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001895 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001896 break;
1897 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001898 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001899 break;
1900 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001901 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001902 break;
1903 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001904 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001905 break;
1906 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001907 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001908 break;
1909 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001910 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001911 break;
1912 }
1913
1914 if (log)
1915 {
1916 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1917 __FUNCTION__,
1918 WEXITSTATUS(status));
1919 }
1920
1921 // Mark the inferior as invalid.
1922 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001923 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001924
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001925 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001926 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001927 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001928 "Could not sync with inferior process.");
1929
1930 if (log)
1931 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1932
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001933 error = SetDefaultPtraceOpts(pid);
1934 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001935 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001936 if (log)
1937 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001938 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001939
1940 // Mark the inferior as invalid.
1941 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001942 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001943
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001944 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001945 }
1946
1947 // Release the master terminal descriptor and pass it off to the
1948 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001949 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1950 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001951
1952 // Set the terminal fd to be in non blocking mode (it simplifies the
1953 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1954 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001955 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1956 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001957 {
1958 if (log)
1959 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001960 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001961
1962 // Mark the inferior as invalid.
1963 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001964 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001965
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001966 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001967 }
1968
1969 if (log)
1970 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1971
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001972 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001973 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001974 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001975 NotifyThreadCreate(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001976
1977 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001978 SetCurrentThreadID (thread_sp->GetID ());
1979 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001980
Todd Fialaaf245d12014-06-30 21:05:18 +00001981 if (log)
1982 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001983 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001984 {
1985 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1986 }
1987 else
1988 {
1989 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001990 __FUNCTION__, error.AsCString ());
1991 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001992 }
1993 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001994 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001995}
1996
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001997::pid_t
1998NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001999{
Todd Fialaaf245d12014-06-30 21:05:18 +00002000 lldb::ThreadSP inferior;
2001 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2002
2003 // Use a map to keep track of the threads which we have attached/need to attach.
2004 Host::TidMap tids_to_attach;
2005 if (pid <= 1)
2006 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002007 error.SetErrorToGenericError();
2008 error.SetErrorString("Attaching to process 1 is not allowed.");
2009 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002010 }
2011
2012 while (Host::FindProcessThreads(pid, tids_to_attach))
2013 {
2014 for (Host::TidMap::iterator it = tids_to_attach.begin();
2015 it != tids_to_attach.end();)
2016 {
2017 if (it->second == false)
2018 {
2019 lldb::tid_t tid = it->first;
2020
2021 // Attach to the requested process.
2022 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002023 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
2024 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002025 {
2026 // No such thread. The thread may have exited.
2027 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002028 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00002029 {
2030 it = tids_to_attach.erase(it);
2031 continue;
2032 }
2033 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002034 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002035 }
2036
2037 int status;
2038 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2039 // At this point we should have a thread stopped if waitpid succeeds.
2040 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2041 {
2042 // No such thread. The thread may have exited.
2043 // More error handling may be needed.
2044 if (errno == ESRCH)
2045 {
2046 it = tids_to_attach.erase(it);
2047 continue;
2048 }
2049 else
2050 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002051 error.SetErrorToErrno();
2052 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002053 }
2054 }
2055
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002056 error = SetDefaultPtraceOpts(tid);
2057 if (error.Fail())
2058 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002059
2060 if (log)
2061 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2062
2063 it->second = true;
2064
2065 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002066 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00002067 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002068
2069 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002070 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002071 NotifyThreadCreate(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002072 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002073 }
2074
2075 // move the loop forward
2076 ++it;
2077 }
2078 }
2079
2080 if (tids_to_attach.size() > 0)
2081 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002082 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002083 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002084 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002085 }
2086 else
2087 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002088 error.SetErrorToGenericError();
2089 error.SetErrorString("No such process.");
2090 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002091 }
2092
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002093 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002094}
2095
Chaoren Lin97ccc292015-02-03 01:51:12 +00002096Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002097NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2098{
2099 long ptrace_opts = 0;
2100
2101 // Have the child raise an event on exit. This is used to keep the child in
2102 // limbo until it is destroyed.
2103 ptrace_opts |= PTRACE_O_TRACEEXIT;
2104
2105 // Have the tracer trace threads which spawn in the inferior process.
2106 // TODO: if we want to support tracing the inferiors' child, add the
2107 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2108 ptrace_opts |= PTRACE_O_TRACECLONE;
2109
2110 // Have the tracer notify us before execve returns
2111 // (needed to disable legacy SIGTRAP generation)
2112 ptrace_opts |= PTRACE_O_TRACEEXEC;
2113
Chaoren Lin97ccc292015-02-03 01:51:12 +00002114 Error error;
2115 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2116 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002117}
2118
2119static ExitType convert_pid_status_to_exit_type (int status)
2120{
2121 if (WIFEXITED (status))
2122 return ExitType::eExitTypeExit;
2123 else if (WIFSIGNALED (status))
2124 return ExitType::eExitTypeSignal;
2125 else if (WIFSTOPPED (status))
2126 return ExitType::eExitTypeStop;
2127 else
2128 {
2129 // We don't know what this is.
2130 return ExitType::eExitTypeInvalid;
2131 }
2132}
2133
2134static int convert_pid_status_to_return_code (int status)
2135{
2136 if (WIFEXITED (status))
2137 return WEXITSTATUS (status);
2138 else if (WIFSIGNALED (status))
2139 return WTERMSIG (status);
2140 else if (WIFSTOPPED (status))
2141 return WSTOPSIG (status);
2142 else
2143 {
2144 // We don't know what this is.
2145 return ExitType::eExitTypeInvalid;
2146 }
2147}
2148
Pavel Labath1107b5a2015-04-17 14:07:49 +00002149// Handles all waitpid events from the inferior process.
2150void
2151NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00002152 bool exited,
2153 int signal,
2154 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00002155{
2156 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2157
Todd Fialaaf245d12014-06-30 21:05:18 +00002158 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002159 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002160
2161 // Handle when the thread exits.
2162 if (exited)
2163 {
2164 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002165 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 +00002166
2167 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002168 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002169
Chaoren Linfa03ad22015-02-03 01:50:42 +00002170 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002171 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002172
Todd Fialaaf245d12014-06-30 21:05:18 +00002173 if (is_main_thread)
2174 {
2175 // We only set the exit status and notify the delegate if we haven't already set the process
2176 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2177 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002178 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00002179 if (!already_notified)
2180 {
2181 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002182 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 +00002183 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002184 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002185
2186 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002187 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002188 }
2189 else
2190 {
2191 if (log)
2192 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2193 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002194 }
2195 else
2196 {
2197 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2198 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2199 // and we would have done an all-stop then.
2200 if (log)
2201 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 +00002202 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00002203 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00002204 }
2205
2206 // Get details on the signal raised.
2207 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00002208 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00002209 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002210 {
2211 // We have retrieved the signal info. Dispatch appropriately.
2212 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002213 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002214 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00002215 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002216 }
2217 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002218 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002219 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002220 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002221 // This is a group stop reception for this tid.
2222 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002223 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002224 NotifyThreadStop (pid, false);
Todd Fialaaf245d12014-06-30 21:05:18 +00002225 }
2226 else
2227 {
2228 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2229
2230 // A return value of ESRCH means the thread/process is no longer on the system,
2231 // so it was killed somehow outside of our control. Either way, we can't do anything
2232 // with it anymore.
2233
Todd Fialaaf245d12014-06-30 21:05:18 +00002234 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002235 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002236
Chaoren Linfa03ad22015-02-03 01:50:42 +00002237 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002238 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002239
Todd Fialaaf245d12014-06-30 21:05:18 +00002240 if (log)
2241 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002242 __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 +00002243
2244 if (is_main_thread)
2245 {
2246 // Notify the delegate - our process is not available but appears to have been killed outside
2247 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00002248 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2249 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002250 }
2251 else
2252 {
2253 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2254 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002255 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 +00002256 }
2257 }
2258 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002259}
2260
2261void
Pavel Labath426bdf82015-04-28 07:51:52 +00002262NativeProcessLinux::WaitForNewThread(::pid_t tid)
2263{
2264 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2265
2266 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2267
2268 if (new_thread_sp)
2269 {
2270 // We are already tracking the thread - we got the event on the new thread (see
2271 // MonitorSignal) before this one. We are done.
2272 return;
2273 }
2274
2275 // The thread is not tracked yet, let's wait for it to appear.
2276 int status = -1;
2277 ::pid_t wait_pid;
2278 do
2279 {
2280 if (log)
2281 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2282 wait_pid = waitpid(tid, &status, __WALL);
2283 }
2284 while (wait_pid == -1 && errno == EINTR);
2285 // Since we are waiting on a specific tid, this must be the creation event. But let's do
2286 // some checks just in case.
2287 if (wait_pid != tid) {
2288 if (log)
2289 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2290 // The only way I know of this could happen is if the whole process was
2291 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2292 return;
2293 }
2294 if (WIFEXITED(status))
2295 {
2296 if (log)
2297 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2298 // Also a very improbable event.
2299 return;
2300 }
2301
2302 siginfo_t info;
2303 Error error = GetSignalInfo(tid, &info);
2304 if (error.Fail())
2305 {
2306 if (log)
2307 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2308 return;
2309 }
2310
2311 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2312 {
2313 // We should be getting a thread creation signal here, but we received something
2314 // else. There isn't much we can do about it now, so we will just log that. Since the
2315 // thread is alive and we are receiving events from it, we shall pretend that it was
2316 // created properly.
2317 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);
2318 }
2319
2320 if (log)
2321 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2322 __FUNCTION__, GetID (), tid);
2323
2324 new_thread_sp = AddThread(tid);
2325 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2326 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002327 NotifyThreadCreate(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00002328}
2329
2330void
Todd Fialaaf245d12014-06-30 21:05:18 +00002331NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2332{
2333 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2334 const bool is_main_thread = (pid == GetID ());
2335
2336 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2337 if (!info)
2338 return;
2339
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002340 Mutex::Locker locker (m_threads_mutex);
2341
Todd Fialaaf245d12014-06-30 21:05:18 +00002342 // See if we can find a thread for this signal.
2343 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2344 if (!thread_sp)
2345 {
2346 if (log)
2347 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2348 }
2349
2350 switch (info->si_code)
2351 {
2352 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2353 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2354 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2355
2356 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2357 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002358 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00002359 // creation.
2360 // We don't want to do anything with the parent thread so we just resume it. In case we
2361 // want to implement "break on thread creation" functionality, we would need to stop
2362 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00002363
Pavel Labath426bdf82015-04-28 07:51:52 +00002364 unsigned long event_message = 0;
2365 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002366 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002367 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002368 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 +00002369 } else
2370 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002371
Pavel Labath5fd24c62015-04-23 09:04:35 +00002372 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002373 break;
2374 }
2375
2376 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002377 {
2378 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002379 if (log)
2380 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002381
Chaoren Linfa03ad22015-02-03 01:50:42 +00002382 // The thread state coordinator needs to reset due to the exec.
Pavel Labathc0765592015-05-06 10:46:34 +00002383 ResetForExec ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002384
2385 // 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 +00002386 if (log)
2387 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2388
2389 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002390 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002391 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2392 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002393 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002394 main_thread_sp = thread_sp;
2395 if (log)
2396 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002397 }
2398 else
2399 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002400 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002401 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002402 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002403 }
2404 }
2405
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002406 m_threads.clear ();
2407
2408 if (main_thread_sp)
2409 {
2410 m_threads.push_back (main_thread_sp);
2411 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002412 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002413 }
2414 else
2415 {
2416 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2417 if (log)
2418 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2419 }
2420
Chaoren Linfa03ad22015-02-03 01:50:42 +00002421 // Tell coordinator about about the "new" (since exec) stopped main thread.
2422 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002423 NotifyThreadCreate(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002424
2425 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2426 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002427 // Let our delegate know we have just exec'd.
2428 NotifyDidExec ();
2429
2430 // If we have a main thread, indicate we are stopped.
2431 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002432
2433 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002434 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002435
Todd Fialaaf245d12014-06-30 21:05:18 +00002436 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002437 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002438
2439 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2440 {
2441 // The inferior process or one of its threads is about to exit.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002442 if (! thread_sp)
2443 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002444
2445 // This thread is currently stopped. It's not actually dead yet, just about to be.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002446 NotifyThreadStop (pid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002447 // The actual stop reason does not matter much, as we are going to resume the thread a
2448 // few lines down. If we ever want to report this state to the debugger, then we should
2449 // invent a new stop reason.
2450 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002451
Todd Fialaaf245d12014-06-30 21:05:18 +00002452 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002453 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002454 data = -1;
2455
2456 if (log)
2457 {
2458 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2459 __FUNCTION__,
2460 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2461 pid,
2462 is_main_thread ? "is main thread" : "not main thread");
2463 }
2464
Todd Fialaaf245d12014-06-30 21:05:18 +00002465 if (is_main_thread)
2466 {
2467 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002468 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002469
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002470 const int signo = static_cast<int> (data);
Pavel Labathc0765592015-05-06 10:46:34 +00002471 RequestThreadResume (pid,
2472 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2473 {
2474 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2475 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002476 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002477
2478 break;
2479 }
2480
2481 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002482 case TRAP_TRACE: // We receive this on single stepping.
2483 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002484 if (thread_sp)
2485 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002486 // If a watchpoint was hit, report it
2487 uint32_t wp_index;
2488 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2489 if (error.Fail() && log)
2490 log->Printf("NativeProcessLinux::%s() "
2491 "received error while checking for watchpoint hits, "
2492 "pid = %" PRIu64 " error = %s",
2493 __FUNCTION__, pid, error.AsCString());
2494 if (wp_index != LLDB_INVALID_INDEX32)
2495 {
2496 MonitorWatchpoint(pid, thread_sp, wp_index);
2497 break;
2498 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002499 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002500 // Otherwise, report step over
2501 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002502 break;
2503
2504 case SI_KERNEL:
2505 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002506 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002507 break;
2508
2509 case SIGTRAP:
2510 case (SIGTRAP | 0x80):
2511 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002512 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2513
2514 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002515 NotifyThreadStop (pid, false);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002516 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002517 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002518
2519
Todd Fialaaf245d12014-06-30 21:05:18 +00002520 // Ignore these signals until we know more about them.
Pavel Labathc0765592015-05-06 10:46:34 +00002521 RequestThreadResume (pid,
2522 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2523 {
2524 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2525 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002526 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002527 break;
2528
2529 default:
2530 assert(false && "Unexpected SIGTRAP code!");
2531 if (log)
2532 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)));
2533 break;
2534
2535 }
2536}
2537
2538void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002539NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2540{
2541 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2542 if (log)
2543 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2544 __FUNCTION__, pid);
2545
2546 if (thread_sp)
2547 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2548
2549 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002550 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002551
2552 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2553 // This would have already happened at the time the Resume() with step operation was signaled.
2554 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2555 // once all running threads have checked in as stopped.
2556 SetCurrentThreadID(pid);
2557 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00002558 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002559}
2560
2561void
2562NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2563{
2564 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2565 if (log)
2566 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2567 __FUNCTION__, pid);
2568
2569 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002570 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002571
2572 // Mark the thread as stopped at breakpoint.
2573 if (thread_sp)
2574 {
2575 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2576 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2577 if (error.Fail())
2578 if (log)
2579 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2580 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002581
2582 auto it = m_threads_stepping_with_breakpoint.find(pid);
2583 if (it != m_threads_stepping_with_breakpoint.end())
2584 {
2585 Error error = RemoveBreakpoint (it->second);
2586 if (error.Fail())
2587 if (log)
2588 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2589 __FUNCTION__, pid, error.AsCString());
2590
2591 m_threads_stepping_with_breakpoint.erase(it);
2592 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2593 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002594 }
2595 else
2596 if (log)
2597 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2598 "warning, cannot process software breakpoint since no thread metadata",
2599 __FUNCTION__, pid);
2600
2601
2602 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002603 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002604}
2605
2606void
2607NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2608{
2609 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2610 if (log)
2611 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2612 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2613 __FUNCTION__, pid, wp_index);
2614
2615 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002616 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002617
2618 // Mark the thread as stopped at watchpoint.
2619 // The address is at (lldb::addr_t)info->si_addr if we need it.
2620 lldbassert(thread_sp && "thread_sp cannot be NULL");
2621 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2622
2623 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002624 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002625}
2626
2627void
Todd Fialaaf245d12014-06-30 21:05:18 +00002628NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2629{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002630 assert (info && "null info");
2631 if (!info)
2632 return;
2633
2634 const int signo = info->si_signo;
2635 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002636
2637 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2638
2639 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2640 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2641 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2642 //
2643 // IOW, user generated signals never generate what we consider to be a
2644 // "crash".
2645 //
2646 // Similarly, ACK signals generated by this monitor.
2647
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002648 Mutex::Locker locker (m_threads_mutex);
2649
Todd Fialaaf245d12014-06-30 21:05:18 +00002650 // See if we can find a thread for this signal.
2651 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2652 if (!thread_sp)
2653 {
2654 if (log)
2655 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2656 }
2657
2658 // Handle the signal.
2659 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2660 {
2661 if (log)
2662 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2663 __FUNCTION__,
2664 GetUnixSignals ().GetSignalAsCString (signo),
2665 signo,
2666 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2667 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002668 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002669 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002670 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002671
Todd Fiala58a2f662014-08-12 17:02:07 +00002672 // Check for new thread notification.
2673 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2674 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002675 // A new thread creation is being signaled. This is one of two parts that come in
2676 // a non-deterministic order. This code handles the case where the new thread event comes
2677 // before the event on the parent thread. For the opposite case see code in
2678 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002679 if (log)
2680 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2681 __FUNCTION__, GetID (), pid);
2682
Pavel Labath5fd24c62015-04-23 09:04:35 +00002683 thread_sp = AddThread(pid);
2684 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2685 // We can now resume the newly created thread.
2686 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2687 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002688 NotifyThreadCreate(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002689 // Done handling.
2690 return;
2691 }
2692
2693 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002694 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002695 {
2696 // This is a tgkill()-based stop.
2697 if (thread_sp)
2698 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002699 if (log)
2700 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2701 __FUNCTION__,
2702 GetID (),
2703 pid);
2704
Chaoren Linaab58632015-02-03 01:50:57 +00002705 // Check that we're not already marked with a stop reason.
2706 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2707 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2708 // and that, without an intervening resume, we received another stop. It is more likely
2709 // that we are missing the marking of a run state somewhere if we find that the thread was
2710 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002711 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2712 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002713
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002714 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002715 if (!StateIsStoppedState (thread_state, false))
2716 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002717 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2718 // Generally, these are not important stops and we don't want to report them as
2719 // they are just used to stop other threads when one thread (the one with the
2720 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2721 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2722 // leave the signal intact if this is the thread that was chosen as the
2723 // triggering thread.
2724 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2725 linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2726 else
2727 linux_thread_sp->SetStoppedBySignal(0);
2728
Chaoren Linaab58632015-02-03 01:50:57 +00002729 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002730 NotifyThreadStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002731 }
2732 else
2733 {
2734 if (log)
2735 {
2736 // Retrieve the signal name if the thread was stopped by a signal.
2737 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002738 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002739 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2740 if (!signal_name)
2741 signal_name = "<no-signal-name>";
2742
2743 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",
2744 __FUNCTION__,
2745 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002746 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002747 StateAsCString (thread_state),
2748 stop_signo,
2749 signal_name);
2750 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002751 // Tell the thread state coordinator about the stop.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002752 NotifyThreadStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002753 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002754 }
2755
2756 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002757 return;
2758 }
2759
2760 if (log)
2761 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2762
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002763 // This thread is stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002764 NotifyThreadStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002765
Todd Fialaaf245d12014-06-30 21:05:18 +00002766 switch (signo)
2767 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002768 case SIGSTOP:
2769 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002770 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002771 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
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004178Error
4179NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4180{
4181 char maps_file_name[32];
4182 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4183
4184 FileSpec maps_file_spec(maps_file_name, false);
4185 if (!maps_file_spec.Exists()) {
4186 file_spec.Clear();
4187 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4188 }
4189
4190 FileSpec module_file_spec(module_path, true);
4191
4192 std::ifstream maps_file(maps_file_name);
4193 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4194 StringRef maps_data(maps_data_str.c_str());
4195
4196 while (!maps_data.empty())
4197 {
4198 StringRef maps_row;
4199 std::tie(maps_row, maps_data) = maps_data.split('\n');
4200
4201 SmallVector<StringRef, 16> maps_columns;
4202 maps_row.split(maps_columns, StringRef(" "), -1, false);
4203
4204 if (maps_columns.size() >= 6)
4205 {
4206 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4207 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4208 return Error();
4209 }
4210 }
4211
4212 file_spec.Clear();
4213 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4214 module_file_spec.GetFilename().AsCString(), GetID());
4215}
Pavel Labathc0765592015-05-06 10:46:34 +00004216
Pavel Labath5eb721e2015-05-07 08:30:31 +00004217Error
Pavel Labathc0765592015-05-06 10:46:34 +00004218NativeProcessLinux::DoResume(
4219 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004220 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00004221 bool error_when_already_running)
4222{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004223 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4224
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004225 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4226 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004227
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004228 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00004229 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004230 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004231
4232 lldbassert(!(error_when_already_running && !is_stopped));
4233
Pavel Labathc0765592015-05-06 10:46:34 +00004234 if (!is_stopped)
4235 {
4236 // It's not an error, just a log, if the error_when_already_running flag is not set.
4237 // This covers cases where, for instance, we're just trying to resume all threads
4238 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004239 if (log)
4240 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4241 __FUNCTION__,
4242 tid);
4243 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00004244 }
4245
4246 // Before we do the resume below, first check if we have a pending
4247 // stop notification this is currently or was previously waiting for
4248 // this thread to stop. This is potentially a buggy situation since
4249 // we're ostensibly waiting for threads to stop before we send out the
4250 // pending notification, and here we are resuming one before we send
4251 // out the pending stop notification.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004252 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004253 {
4254 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4255 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004256 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 +00004257 }
4258 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0)
4259 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004260 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 +00004261 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4262 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004263 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00004264 __FUNCTION__,
4265 m_pending_notification_up->triggering_tid,
4266 tid);
4267 }
4268 }
4269 }
4270
4271 // Request a resume. We expect this to be synchronous and the system
4272 // to reflect it is running after this completes.
4273 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004274 if (error.Success())
4275 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00004276 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004277 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004278 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00004279 __FUNCTION__, tid, error.AsCString ());
4280 }
4281
Pavel Labath5eb721e2015-05-07 08:30:31 +00004282 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004283}
4284
4285//===----------------------------------------------------------------------===//
4286
4287void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004288NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004289 const ThreadIDSet &wait_for_stop_tids)
Pavel Labathc0765592015-05-06 10:46:34 +00004290{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004291 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004292 std::lock_guard<std::mutex> lock(m_event_mutex);
4293
Pavel Labath5eb721e2015-05-07 08:30:31 +00004294 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004295 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004296 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)",
Pavel Labathc0765592015-05-06 10:46:34 +00004297 __FUNCTION__, triggering_tid, wait_for_stop_tids.size());
4298 }
4299
Pavel Labathed89c7f2015-05-06 12:22:37 +00004300 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labath337f3eb2015-05-08 08:57:45 +00004301 triggering_tid, wait_for_stop_tids, ThreadIDSet())));
Pavel Labathc0765592015-05-06 10:46:34 +00004302
Pavel Labath5eb721e2015-05-07 08:30:31 +00004303 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004304 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004305 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004306 }
4307}
4308
4309void
Pavel Labath337f3eb2015-05-08 08:57:45 +00004310NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004311{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004312 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004313 std::lock_guard<std::mutex> lock(m_event_mutex);
4314
Pavel Labath5eb721e2015-05-07 08:30:31 +00004315 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004316 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004317 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004318 __FUNCTION__, triggering_tid);
4319 }
4320
Pavel Labath337f3eb2015-05-08 08:57:45 +00004321 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00004322
Pavel Labath5eb721e2015-05-07 08:30:31 +00004323 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004324 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004325 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004326 }
4327}
4328
4329void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004330NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004331 lldb::tid_t skip_stop_request_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004332{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004333 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004334 std::lock_guard<std::mutex> lock(m_event_mutex);
4335
Pavel Labath5eb721e2015-05-07 08:30:31 +00004336 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004337 {
Pavel Labath337f3eb2015-05-08 08:57:45 +00004338 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tid: %" PRIu64 ")",
4339 __FUNCTION__, triggering_tid, skip_stop_request_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004340 }
4341
Pavel Labathed89c7f2015-05-06 12:22:37 +00004342 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labathc0765592015-05-06 10:46:34 +00004343 triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004344 ThreadIDSet(),
4345 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : ThreadIDSet ())));
Pavel Labathc0765592015-05-06 10:46:34 +00004346
Pavel Labath5eb721e2015-05-07 08:30:31 +00004347 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004348 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004349 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004350 }
4351}
4352
4353void
4354NativeProcessLinux::SignalIfRequirementsSatisfied()
4355{
4356 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4357 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00004358 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4359 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004360 m_pending_notification_up.reset();
4361 }
4362}
4363
4364bool
4365NativeProcessLinux::RequestStopOnAllSpecifiedThreads()
4366{
4367 // Request a stop for all the thread stops that need to be stopped
4368 // and are not already known to be stopped. Keep a list of all the
4369 // threads from which we still need to hear a stop reply.
4370
4371 ThreadIDSet sent_tids;
4372 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4373 {
4374 // Validate we know about all tids for which we must first receive a stop before
4375 // triggering the deferred stop notification.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004376 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4377 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004378
4379 // If the pending stop thread is currently running, we need to send it a stop request.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004380 if (StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00004381 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004382 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00004383 sent_tids.insert (tid);
4384 }
4385 }
4386 // We only need to wait for the sent_tids - so swap our wait set
4387 // to the sent tids. The rest are already stopped and we won't
4388 // be receiving stop notifications for them.
4389 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4390
4391 // Succeeded, keep running.
4392 return true;
4393}
4394
4395void
4396NativeProcessLinux::RequestStopOnAllRunningThreads()
4397{
4398 // Request a stop for all the thread stops that need to be stopped
4399 // and are not already known to be stopped. Keep a list of all the
4400 // threads from which we still need to hear a stop reply.
4401
4402 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004403 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00004404 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004405 // We only care about running threads
4406 if (StateIsStoppedState(thread_sp->GetState(), true))
4407 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00004408
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004409 const lldb::tid_t tid = thread_sp->GetID();
Pavel Labathc0765592015-05-06 10:46:34 +00004410
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004411 // Request this thread stop if the tid stop request is not explicitly ignored.
4412 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0;
4413 if (!skip_stop_request)
4414 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4415
4416 // Even if we skipped sending the stop request for other reasons (like stepping),
4417 // we still need to wait for that stepping thread to notify completion/stop.
4418 sent_tids.insert (tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004419 }
4420
4421 // Set the wait list to the set of tids for which we requested stops.
4422 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4423}
4424
Pavel Labathc0765592015-05-06 10:46:34 +00004425
Pavel Labath5eb721e2015-05-07 08:30:31 +00004426Error
4427NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004428{
4429 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004430 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4431 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004432
4433 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004434 auto& context = thread_sp->GetThreadContext();
4435 const auto stop_was_requested = context.stop_requested;
4436 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00004437
4438 // If we have a pending notification, remove this from the set.
4439 if (m_pending_notification_up)
4440 {
4441 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4442 SignalIfRequirementsSatisfied();
4443 }
4444
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004445 Error error;
4446 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00004447 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004448 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004449 // We can end up here if stop was initiated by LLGS but by this time a
4450 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004451 if (log)
4452 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004453 error = context.request_resume_function (tid, true);
4454 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004455 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004456 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
4457 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00004458 }
4459 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004460 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004461}
4462
4463void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004464NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00004465{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004466 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4467 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004468 {
4469 // Yikes - we've already got a pending signal notification in progress.
4470 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004471 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 +00004472 __FUNCTION__,
4473 m_pending_notification_up->triggering_tid,
4474 notification_up->triggering_tid);
4475 }
4476 m_pending_notification_up = std::move(notification_up);
4477
4478 if (m_pending_notification_up->request_stop_on_all_unstopped_threads)
4479 RequestStopOnAllRunningThreads();
4480 else
4481 {
4482 if (!RequestStopOnAllSpecifiedThreads())
4483 return;
4484 }
4485
Pavel Labathed89c7f2015-05-06 12:22:37 +00004486 SignalIfRequirementsSatisfied();
Pavel Labathc0765592015-05-06 10:46:34 +00004487}
4488
4489void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004490NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004491{
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004492 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4493 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004494
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004495 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00004496 {
4497 // We will need to wait for this new thread to stop as well before firing the
4498 // notification.
4499 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004500 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00004501 }
4502}
4503
4504void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004505NativeProcessLinux::ThreadDidDie (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004506{
Pavel Labathc0765592015-05-06 10:46:34 +00004507 // If we have a pending notification, remove this from the set.
4508 if (m_pending_notification_up)
4509 {
4510 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4511 SignalIfRequirementsSatisfied();
4512 }
4513}
4514
Pavel Labath5eb721e2015-05-07 08:30:31 +00004515Error
4516NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004517{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004518 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004519 std::lock_guard<std::mutex> lock(m_event_mutex);
4520
Pavel Labath5eb721e2015-05-07 08:30:31 +00004521 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004522 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004523 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)",
Pavel Labathc0765592015-05-06 10:46:34 +00004524 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
4525 }
4526
Pavel Labath5eb721e2015-05-07 08:30:31 +00004527 Error error = ThreadDidStop (tid, initiated_by_llgs);
Pavel Labathc0765592015-05-06 10:46:34 +00004528
Pavel Labath5eb721e2015-05-07 08:30:31 +00004529 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004530 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004531 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004532 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004533
4534 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004535}
4536
Pavel Labath5eb721e2015-05-07 08:30:31 +00004537Error
Pavel Labathc0765592015-05-06 10:46:34 +00004538NativeProcessLinux::RequestThreadResume (lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004539 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004540{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004541 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004542 std::lock_guard<std::mutex> lock(m_event_mutex);
4543
Pavel Labath5eb721e2015-05-07 08:30:31 +00004544 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004545 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004546 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004547 __FUNCTION__, tid);
4548 }
4549
Pavel Labath5eb721e2015-05-07 08:30:31 +00004550 Error error = DoResume(tid, request_thread_resume_function, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004551
Pavel Labath5eb721e2015-05-07 08:30:31 +00004552 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004553 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004554 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004555 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004556
4557 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004558}
4559
Pavel Labath5eb721e2015-05-07 08:30:31 +00004560Error
Pavel Labathc0765592015-05-06 10:46:34 +00004561NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004562 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004563{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004564 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004565 std::lock_guard<std::mutex> lock(m_event_mutex);
4566
Pavel Labath5eb721e2015-05-07 08:30:31 +00004567 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004568 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004569 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004570 __FUNCTION__, tid);
4571 }
4572
Pavel Labath5eb721e2015-05-07 08:30:31 +00004573 Error error = DoResume (tid, request_thread_resume_function, false);
Pavel Labathc0765592015-05-06 10:46:34 +00004574
Pavel Labath5eb721e2015-05-07 08:30:31 +00004575 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004576 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004577 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004578 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004579
4580 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004581}
4582
4583void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004584NativeProcessLinux::NotifyThreadCreate(lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004585{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004586 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004587 std::lock_guard<std::mutex> lock(m_event_mutex);
4588
Pavel Labath5eb721e2015-05-07 08:30:31 +00004589 if (log)
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004590 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004591
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004592 ThreadWasCreated(tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004593
Pavel Labath5eb721e2015-05-07 08:30:31 +00004594 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004595 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004596 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004597 }
4598}
4599
4600void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004601NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004602{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004603 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004604 std::lock_guard<std::mutex> lock(m_event_mutex);
4605
Pavel Labath5eb721e2015-05-07 08:30:31 +00004606 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004607 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004608 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004609 }
4610
Pavel Labath5eb721e2015-05-07 08:30:31 +00004611 ThreadDidDie(tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004612
Pavel Labath5eb721e2015-05-07 08:30:31 +00004613 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004614 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004615 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004616 }
4617}
4618
4619void
4620NativeProcessLinux::ResetForExec ()
4621{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004622 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004623 std::lock_guard<std::mutex> lock(m_event_mutex);
4624
Pavel Labath5eb721e2015-05-07 08:30:31 +00004625 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004626 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004627 log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004628 }
4629
4630 // Clear the pending notification if there was one.
4631 m_pending_notification_up.reset ();
4632
Pavel Labath5eb721e2015-05-07 08:30:31 +00004633 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004634 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004635 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004636 }
4637}