blob: 5491efec43c923e014a958be892ce881d5175b6d [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/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000058
Tamas Berghammerd8584872015-02-06 10:57:40 +000059#include <sys/types.h>
60#include <sys/uio.h>
61#include <sys/user.h>
62#include <sys/wait.h>
63
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000064#if defined (__arm64__) || defined (__aarch64__)
65// NT_PRSTATUS and NT_FPREGSET definition
66#include <elf.h>
67#endif
68
Vince Harron8b335672015-05-12 01:10:56 +000069#include "lldb/Host/linux/Personality.h"
70#include "lldb/Host/linux/Ptrace.h"
71#include "lldb/Host/linux/Signalfd.h"
72#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000073
Todd Fiala0bce1b62014-08-17 00:10:50 +000074#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000075
76// Support hardware breakpoints in case it has not been defined
77#ifndef TRAP_HWBKPT
78 #define TRAP_HWBKPT 4
79#endif
80
Todd Fialaaf245d12014-06-30 21:05:18 +000081// We disable the tracing of ptrace calls for integration builds to
82// avoid the additional indirection and checks.
83#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +000084#define PTRACE(req, pid, addr, data, data_size, error) \
85 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +000086#else
Chaoren Lin97ccc292015-02-03 01:51:12 +000087#define PTRACE(req, pid, addr, data, data_size, error) \
88 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +000089#endif
90
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000091using namespace lldb;
92using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000093using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000094using namespace llvm;
95
Todd Fialaaf245d12014-06-30 21:05:18 +000096// Private bits we only need internally.
97namespace
98{
Todd Fialaaf245d12014-06-30 21:05:18 +000099 const UnixSignals&
100 GetUnixSignals ()
101 {
102 static process_linux::LinuxSignals signals;
103 return signals;
104 }
105
Todd Fialaaf245d12014-06-30 21:05:18 +0000106 Error
107 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
108 {
109 // Grab process info for the running process.
110 ProcessInstanceInfo process_info;
111 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000112 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000113
114 // Resolve the executable module.
115 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000116 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000117 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
118 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000119 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000120 exe_module_sp,
121 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
122
123 if (!error.Success ())
124 return error;
125
126 // Check if we've got our architecture from the exe_module.
127 arch = exe_module_sp->GetArchitecture ();
128 if (arch.IsValid ())
129 return Error();
130 else
131 return Error("failed to retrieve a valid architecture from the exe module");
132 }
133
134 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000135 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000136 {
137 uint8_t *ptr = (uint8_t *)bytes;
138 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
139 for(uint32_t i=0; i<loop_count; i++)
140 {
141 s.Printf ("[%x]", *ptr);
142 ptr++;
143 }
144 }
145
146 void
147 PtraceDisplayBytes(int &req, void *data, size_t data_size)
148 {
149 StreamString buf;
150 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
151 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
152
153 if (verbose_log)
154 {
155 switch(req)
156 {
157 case PTRACE_POKETEXT:
158 {
159 DisplayBytes(buf, &data, 8);
160 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
161 break;
162 }
163 case PTRACE_POKEDATA:
164 {
165 DisplayBytes(buf, &data, 8);
166 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
167 break;
168 }
169 case PTRACE_POKEUSER:
170 {
171 DisplayBytes(buf, &data, 8);
172 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
173 break;
174 }
175 case PTRACE_SETREGS:
176 {
177 DisplayBytes(buf, data, data_size);
178 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
179 break;
180 }
181 case PTRACE_SETFPREGS:
182 {
183 DisplayBytes(buf, data, data_size);
184 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
185 break;
186 }
187 case PTRACE_SETSIGINFO:
188 {
189 DisplayBytes(buf, data, sizeof(siginfo_t));
190 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
191 break;
192 }
193 case PTRACE_SETREGSET:
194 {
195 // Extract iov_base from data, which is a pointer to the struct IOVEC
196 DisplayBytes(buf, *(void **)data, data_size);
197 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
198 break;
199 }
200 default:
201 {
202 }
203 }
204 }
205 }
206
207 // Wrapper for ptrace to catch errors and log calls.
208 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
209 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000210 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
211 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000212 {
213 long int result;
214
215 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
216
217 PtraceDisplayBytes(req, data, data_size);
218
Chaoren Lin97ccc292015-02-03 01:51:12 +0000219 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000220 errno = 0;
221 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000222 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000223 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000224 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000225
Chaoren Lin97ccc292015-02-03 01:51:12 +0000226 if (result == -1)
227 error.SetErrorToErrno();
228
Todd Fialaaf245d12014-06-30 21:05:18 +0000229 if (log)
230 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
231 reqName, pid, addr, data, data_size, result, file, line);
232
233 PtraceDisplayBytes(req, data, data_size);
234
Chaoren Lin97ccc292015-02-03 01:51:12 +0000235 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000236 {
237 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000238 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000239 {
240 case ESRCH: str = "ESRCH"; break;
241 case EINVAL: str = "EINVAL"; break;
242 case EBUSY: str = "EBUSY"; break;
243 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000244 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000245 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000246 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000247 }
248
249 return result;
250 }
251
252#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
253 // Wrapper for ptrace when logging is not required.
254 // Sets errno to 0 prior to calling ptrace.
255 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000256 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000257 {
258 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000259
260 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000261 errno = 0;
262 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000263 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000264 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000265 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000266
267 if (result == -1)
268 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000269 return result;
270 }
271#endif
272
273 //------------------------------------------------------------------------------
274 // Static implementations of NativeProcessLinux::ReadMemory and
275 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
276 // functions without needed to go thru the thread funnel.
277
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000278 size_t
279 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000280 lldb::pid_t pid,
281 lldb::addr_t vm_addr,
282 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000283 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000284 Error &error)
285 {
286 // ptrace word size is determined by the host, not the child
287 static const unsigned word_size = sizeof(void*);
288 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000289 size_t bytes_read;
290 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000291 long data;
292
293 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
294 if (log)
295 ProcessPOSIXLog::IncNestLevel();
296 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
297 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
298 pid, word_size, (void*)vm_addr, buf, size);
299
300 assert(sizeof(data) >= word_size);
301 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
302 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000303 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
304 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000305 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 if (log)
307 ProcessPOSIXLog::DecNestLevel();
308 return bytes_read;
309 }
310
311 remainder = size - bytes_read;
312 remainder = remainder > word_size ? word_size : remainder;
313
314 // Copy the data into our buffer
315 for (unsigned i = 0; i < remainder; ++i)
316 dst[i] = ((data >> i*8) & 0xFF);
317
318 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
319 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
320 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
321 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
322 {
323 uintptr_t print_dst = 0;
324 // Format bytes from data by moving into print_dst for log output
325 for (unsigned i = 0; i < remainder; ++i)
326 print_dst |= (((data >> i*8) & 0xFF) << i*8);
327 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
328 (void*)vm_addr, print_dst, (unsigned long)data);
329 }
330
331 vm_addr += word_size;
332 dst += word_size;
333 }
334
335 if (log)
336 ProcessPOSIXLog::DecNestLevel();
337 return bytes_read;
338 }
339
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000340 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000341 DoWriteMemory(
342 lldb::pid_t pid,
343 lldb::addr_t vm_addr,
344 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000345 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000346 Error &error)
347 {
348 // ptrace word size is determined by the host, not the child
349 static const unsigned word_size = sizeof(void*);
350 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000351 size_t bytes_written = 0;
352 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000353
354 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
355 if (log)
356 ProcessPOSIXLog::IncNestLevel();
357 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
358 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
359 pid, word_size, (void*)vm_addr, buf, size);
360
361 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
362 {
363 remainder = size - bytes_written;
364 remainder = remainder > word_size ? word_size : remainder;
365
366 if (remainder == word_size)
367 {
368 unsigned long data = 0;
369 assert(sizeof(data) >= word_size);
370 for (unsigned i = 0; i < word_size; ++i)
371 data |= (unsigned long)src[i] << i*8;
372
373 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
374 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
375 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
376 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
377 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000378 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000379
Chaoren Lin97ccc292015-02-03 01:51:12 +0000380 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000381 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000382 if (log)
383 ProcessPOSIXLog::DecNestLevel();
384 return bytes_written;
385 }
386 }
387 else
388 {
389 unsigned char buff[8];
390 if (DoReadMemory(pid, vm_addr,
391 buff, word_size, error) != word_size)
392 {
393 if (log)
394 ProcessPOSIXLog::DecNestLevel();
395 return bytes_written;
396 }
397
398 memcpy(buff, src, remainder);
399
400 if (DoWriteMemory(pid, vm_addr,
401 buff, word_size, error) != word_size)
402 {
403 if (log)
404 ProcessPOSIXLog::DecNestLevel();
405 return bytes_written;
406 }
407
408 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
409 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
410 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
411 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
412 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000413 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000414 }
415
416 vm_addr += word_size;
417 src += word_size;
418 }
419 if (log)
420 ProcessPOSIXLog::DecNestLevel();
421 return bytes_written;
422 }
423
424 //------------------------------------------------------------------------------
425 /// @class Operation
426 /// @brief Represents a NativeProcessLinux operation.
427 ///
428 /// Under Linux, it is not possible to ptrace() from any other thread but the
429 /// one that spawned or attached to the process from the start. Therefore, when
430 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
431 /// process the operation must be "funneled" to a specific thread to perform the
432 /// task. The Operation class provides an abstract base for all services the
433 /// NativeProcessLinux must perform via the single virtual function Execute, thus
434 /// encapsulating the code that needs to run in the privileged context.
435 class Operation
436 {
437 public:
438 Operation () : m_error() { }
439
440 virtual
441 ~Operation() {}
442
443 virtual void
444 Execute (NativeProcessLinux *process) = 0;
445
446 const Error &
447 GetError () const { return m_error; }
448
449 protected:
450 Error m_error;
451 };
452
453 //------------------------------------------------------------------------------
454 /// @class ReadOperation
455 /// @brief Implements NativeProcessLinux::ReadMemory.
456 class ReadOperation : public Operation
457 {
458 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000459 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000460 lldb::addr_t addr,
461 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000462 size_t size,
463 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000464 Operation (),
465 m_addr (addr),
466 m_buff (buff),
467 m_size (size),
468 m_result (result)
469 {
470 }
471
472 void Execute (NativeProcessLinux *process) override;
473
474 private:
475 lldb::addr_t m_addr;
476 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000477 size_t m_size;
478 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000479 };
480
481 void
482 ReadOperation::Execute (NativeProcessLinux *process)
483 {
484 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
485 }
486
487 //------------------------------------------------------------------------------
488 /// @class WriteOperation
489 /// @brief Implements NativeProcessLinux::WriteMemory.
490 class WriteOperation : public Operation
491 {
492 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000493 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000494 lldb::addr_t addr,
495 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000496 size_t size,
497 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000498 Operation (),
499 m_addr (addr),
500 m_buff (buff),
501 m_size (size),
502 m_result (result)
503 {
504 }
505
506 void Execute (NativeProcessLinux *process) override;
507
508 private:
509 lldb::addr_t m_addr;
510 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000511 size_t m_size;
512 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000513 };
514
515 void
516 WriteOperation::Execute(NativeProcessLinux *process)
517 {
518 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
519 }
520
521 //------------------------------------------------------------------------------
522 /// @class ReadRegOperation
523 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
524 class ReadRegOperation : public Operation
525 {
526 public:
527 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000528 RegisterValue &value)
529 : m_tid(tid),
530 m_offset(static_cast<uintptr_t> (offset)),
531 m_reg_name(reg_name),
532 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000533 { }
534
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000535 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000536
537 private:
538 lldb::tid_t m_tid;
539 uintptr_t m_offset;
540 const char *m_reg_name;
541 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000542 };
543
544 void
545 ReadRegOperation::Execute(NativeProcessLinux *monitor)
546 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000547#if defined (__arm64__) || defined (__aarch64__)
548 if (m_offset > sizeof(struct user_pt_regs))
549 {
550 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
551 if (offset > sizeof(struct user_fpsimd_state))
552 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000553 m_error.SetErrorString("invalid offset value");
554 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000555 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000556 elf_fpregset_t regs;
557 int regset = NT_FPREGSET;
558 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000559
Chaoren Lin97ccc292015-02-03 01:51:12 +0000560 ioVec.iov_base = &regs;
561 ioVec.iov_len = sizeof regs;
562 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
563 if (m_error.Success())
564 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000565 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000566 if (monitor->GetArchitecture(arch))
567 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000568 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000569 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000570 }
571 }
572 else
573 {
574 elf_gregset_t regs;
575 int regset = NT_PRSTATUS;
576 struct iovec ioVec;
577
578 ioVec.iov_base = &regs;
579 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000580 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
581 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000582 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000583 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000584 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000585 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000586 else
587 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000588 }
589 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000590#elif defined (__mips__)
591 elf_gregset_t regs;
592 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
593 if (m_error.Success())
594 {
595 lldb_private::ArchSpec arch;
596 if (monitor->GetArchitecture(arch))
597 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
598 else
599 m_error.SetErrorString("failed to get architecture");
600 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000601#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000602 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
603
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000604 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 +0000605 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000606 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000607
Todd Fialaaf245d12014-06-30 21:05:18 +0000608 if (log)
609 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
610 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000611#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 }
613
614 //------------------------------------------------------------------------------
615 /// @class WriteRegOperation
616 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
617 class WriteRegOperation : public Operation
618 {
619 public:
620 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000621 const RegisterValue &value)
622 : m_tid(tid),
623 m_offset(offset),
624 m_reg_name(reg_name),
625 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000626 { }
627
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000628 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000629
630 private:
631 lldb::tid_t m_tid;
632 uintptr_t m_offset;
633 const char *m_reg_name;
634 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000635 };
636
637 void
638 WriteRegOperation::Execute(NativeProcessLinux *monitor)
639 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000640#if defined (__arm64__) || defined (__aarch64__)
641 if (m_offset > sizeof(struct user_pt_regs))
642 {
643 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
644 if (offset > sizeof(struct user_fpsimd_state))
645 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000646 m_error.SetErrorString("invalid offset value");
647 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000648 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000649 elf_fpregset_t regs;
650 int regset = NT_FPREGSET;
651 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000652
Chaoren Lin97ccc292015-02-03 01:51:12 +0000653 ioVec.iov_base = &regs;
654 ioVec.iov_len = sizeof regs;
655 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000656 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000657 {
658 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
659 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000660 }
661 }
662 else
663 {
664 elf_gregset_t regs;
665 int regset = NT_PRSTATUS;
666 struct iovec ioVec;
667
668 ioVec.iov_base = &regs;
669 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000670 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000671 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000672 {
673 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000674 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000675 }
676 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000677#elif defined (__mips__)
678 elf_gregset_t regs;
679 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
680 if (m_error.Success())
681 {
682 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
683 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
684 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000685#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000686 void* buf;
687 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
688
689 buf = (void*) m_value.GetAsUInt64();
690
691 if (log)
692 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000693 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000694#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000695 }
696
697 //------------------------------------------------------------------------------
698 /// @class ReadGPROperation
699 /// @brief Implements NativeProcessLinux::ReadGPR.
700 class ReadGPROperation : public Operation
701 {
702 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000703 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
704 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000705 { }
706
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000707 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000708
709 private:
710 lldb::tid_t m_tid;
711 void *m_buf;
712 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000713 };
714
715 void
716 ReadGPROperation::Execute(NativeProcessLinux *monitor)
717 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000718#if defined (__arm64__) || defined (__aarch64__)
719 int regset = NT_PRSTATUS;
720 struct iovec ioVec;
721
722 ioVec.iov_base = m_buf;
723 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000724 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000725#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000726 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000727#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000728 }
729
730 //------------------------------------------------------------------------------
731 /// @class ReadFPROperation
732 /// @brief Implements NativeProcessLinux::ReadFPR.
733 class ReadFPROperation : public Operation
734 {
735 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000736 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
737 : m_tid(tid),
738 m_buf(buf),
739 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000740 { }
741
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000742 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000743
744 private:
745 lldb::tid_t m_tid;
746 void *m_buf;
747 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000748 };
749
750 void
751 ReadFPROperation::Execute(NativeProcessLinux *monitor)
752 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000753#if defined (__arm64__) || defined (__aarch64__)
754 int regset = NT_FPREGSET;
755 struct iovec ioVec;
756
757 ioVec.iov_base = m_buf;
758 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000759 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000760#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000761 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000762#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000763 }
764
765 //------------------------------------------------------------------------------
766 /// @class ReadRegisterSetOperation
767 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
768 class ReadRegisterSetOperation : public Operation
769 {
770 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000771 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
772 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000773 { }
774
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000775 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000776
777 private:
778 lldb::tid_t m_tid;
779 void *m_buf;
780 size_t m_buf_size;
781 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000782 };
783
784 void
785 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
786 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000787 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000788 }
789
790 //------------------------------------------------------------------------------
791 /// @class WriteGPROperation
792 /// @brief Implements NativeProcessLinux::WriteGPR.
793 class WriteGPROperation : public Operation
794 {
795 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000796 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
797 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 { }
799
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000800 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000801
802 private:
803 lldb::tid_t m_tid;
804 void *m_buf;
805 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000806 };
807
808 void
809 WriteGPROperation::Execute(NativeProcessLinux *monitor)
810 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000811#if defined (__arm64__) || defined (__aarch64__)
812 int regset = NT_PRSTATUS;
813 struct iovec ioVec;
814
815 ioVec.iov_base = m_buf;
816 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000817 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000818#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000819 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000820#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000821 }
822
823 //------------------------------------------------------------------------------
824 /// @class WriteFPROperation
825 /// @brief Implements NativeProcessLinux::WriteFPR.
826 class WriteFPROperation : public Operation
827 {
828 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000829 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
830 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000831 { }
832
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000833 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000834
835 private:
836 lldb::tid_t m_tid;
837 void *m_buf;
838 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000839 };
840
841 void
842 WriteFPROperation::Execute(NativeProcessLinux *monitor)
843 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000844#if defined (__arm64__) || defined (__aarch64__)
845 int regset = NT_FPREGSET;
846 struct iovec ioVec;
847
848 ioVec.iov_base = m_buf;
849 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000850 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000851#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000852 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000853#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000854 }
855
856 //------------------------------------------------------------------------------
857 /// @class WriteRegisterSetOperation
858 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
859 class WriteRegisterSetOperation : public Operation
860 {
861 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000862 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
863 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000864 { }
865
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000866 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000867
868 private:
869 lldb::tid_t m_tid;
870 void *m_buf;
871 size_t m_buf_size;
872 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000873 };
874
875 void
876 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
877 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000878 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000879 }
880
881 //------------------------------------------------------------------------------
882 /// @class ResumeOperation
883 /// @brief Implements NativeProcessLinux::Resume.
884 class ResumeOperation : public Operation
885 {
886 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000887 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
888 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000889
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000890 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000891
892 private:
893 lldb::tid_t m_tid;
894 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000895 };
896
897 void
898 ResumeOperation::Execute(NativeProcessLinux *monitor)
899 {
900 intptr_t data = 0;
901
902 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
903 data = m_signo;
904
Chaoren Lin97ccc292015-02-03 01:51:12 +0000905 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
906 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000907 {
908 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
909
910 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000911 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000912 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000913 }
914
915 //------------------------------------------------------------------------------
916 /// @class SingleStepOperation
917 /// @brief Implements NativeProcessLinux::SingleStep.
918 class SingleStepOperation : public Operation
919 {
920 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000921 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
922 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000923
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000924 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000925
926 private:
927 lldb::tid_t m_tid;
928 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000929 };
930
931 void
932 SingleStepOperation::Execute(NativeProcessLinux *monitor)
933 {
934 intptr_t data = 0;
935
936 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
937 data = m_signo;
938
Chaoren Lin97ccc292015-02-03 01:51:12 +0000939 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000940 }
941
942 //------------------------------------------------------------------------------
943 /// @class SiginfoOperation
944 /// @brief Implements NativeProcessLinux::GetSignalInfo.
945 class SiginfoOperation : public Operation
946 {
947 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000948 SiginfoOperation(lldb::tid_t tid, void *info)
949 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000950
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000951 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000952
953 private:
954 lldb::tid_t m_tid;
955 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +0000956 };
957
958 void
959 SiginfoOperation::Execute(NativeProcessLinux *monitor)
960 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000961 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000962 }
963
964 //------------------------------------------------------------------------------
965 /// @class EventMessageOperation
966 /// @brief Implements NativeProcessLinux::GetEventMessage.
967 class EventMessageOperation : public Operation
968 {
969 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000970 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
971 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000972
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000973 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000974
975 private:
976 lldb::tid_t m_tid;
977 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +0000978 };
979
980 void
981 EventMessageOperation::Execute(NativeProcessLinux *monitor)
982 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000983 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000984 }
985
986 class DetachOperation : public Operation
987 {
988 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000989 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000990
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000991 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000992
993 private:
994 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000995 };
996
997 void
998 DetachOperation::Execute(NativeProcessLinux *monitor)
999 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001000 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001001 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001002} // end of anonymous namespace
1003
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001004// Simple helper function to ensure flags are enabled on the given file
1005// descriptor.
1006static Error
1007EnsureFDFlags(int fd, int flags)
1008{
1009 Error error;
1010
1011 int status = fcntl(fd, F_GETFL);
1012 if (status == -1)
1013 {
1014 error.SetErrorToErrno();
1015 return error;
1016 }
1017
1018 if (fcntl(fd, F_SETFL, status | flags) == -1)
1019 {
1020 error.SetErrorToErrno();
1021 return error;
1022 }
1023
1024 return error;
1025}
1026
1027// This class encapsulates the privileged thread which performs all ptrace and wait operations on
1028// the inferior. The thread consists of a main loop which waits for events and processes them
1029// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1030// the inferior process. Upon receiving this signal we do a waitpid to get more information
1031// and dispatch to NativeProcessLinux::MonitorCallback.
1032// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1033// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1034// pipe, and the completion of the operation is signalled over the semaphore.
1035// - thread exit event: this is signaled from the Monitor destructor by closing the write end
1036// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001037class NativeProcessLinux::Monitor
1038{
Pavel Labath1107b5a2015-04-17 14:07:49 +00001039private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001040 // The initial monitor operation (launch or attach). It returns a inferior process id.
1041 std::unique_ptr<InitialOperation> m_initial_operation_up;
1042
1043 ::pid_t m_child_pid = -1;
1044 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001045
1046 enum { READ, WRITE };
1047 int m_pipefd[2] = {-1, -1};
1048 int m_signal_fd = -1;
1049 HostThread m_thread;
1050
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001051 // current operation which must be executed on the priviliged thread
1052 Mutex m_operation_mutex;
1053 Operation *m_operation = nullptr;
1054 sem_t m_operation_sem;
1055 Error m_operation_error;
1056
Pavel Labath45f5cb32015-05-05 15:05:50 +00001057 unsigned m_operation_nesting_level = 0;
1058
1059 static constexpr char operation_command = 'o';
1060 static constexpr char begin_block_command = '{';
1061 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001062
Pavel Labath1107b5a2015-04-17 14:07:49 +00001063 void
1064 HandleSignals();
1065
1066 void
1067 HandleWait();
1068
1069 // Returns true if the thread should exit.
1070 bool
1071 HandleCommands();
1072
1073 void
1074 MainLoop();
1075
1076 static void *
1077 RunMonitor(void *arg);
1078
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001079 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001080 WaitForAck();
1081
1082 void
1083 BeginOperationBlock()
1084 {
1085 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
1086 WaitForAck();
1087 }
1088
1089 void
1090 EndOperationBlock()
1091 {
1092 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
1093 WaitForAck();
1094 }
1095
Pavel Labath1107b5a2015-04-17 14:07:49 +00001096public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001097 Monitor(const InitialOperation &initial_operation,
1098 NativeProcessLinux *native_process)
1099 : m_initial_operation_up(new InitialOperation(initial_operation)),
1100 m_native_process(native_process)
1101 {
1102 sem_init(&m_operation_sem, 0, 0);
1103 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001104
1105 ~Monitor();
1106
1107 Error
1108 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001109
1110 void
Pavel Labath45f5cb32015-05-05 15:05:50 +00001111 Terminate();
1112
1113 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001114 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001115
1116 class ScopedOperationLock {
1117 Monitor &m_monitor;
1118
1119 public:
1120 ScopedOperationLock(Monitor &monitor)
1121 : m_monitor(monitor)
1122 { m_monitor.BeginOperationBlock(); }
1123
1124 ~ScopedOperationLock()
1125 { m_monitor.EndOperationBlock(); }
1126 };
Pavel Labath1107b5a2015-04-17 14:07:49 +00001127};
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001128constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +00001129constexpr char NativeProcessLinux::Monitor::begin_block_command;
1130constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001131
1132Error
1133NativeProcessLinux::Monitor::Initialize()
1134{
1135 Error error;
1136
1137 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1138 // listening for these signals over a signalfd file descriptors. This allows us to wait for
1139 // multiple kinds of events with select.
1140 sigset_t signals;
1141 sigemptyset(&signals);
1142 sigaddset(&signals, SIGCHLD);
1143 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1144 if (m_signal_fd < 0)
1145 {
1146 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1147 __FUNCTION__, strerror(errno));
1148
1149 }
1150
1151 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1152 {
1153 error.SetErrorToErrno();
1154 return error;
1155 }
1156
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001157 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1158 return error;
1159 }
1160
1161 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1162 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001163 if (!m_thread.IsJoinable())
1164 return Error("Failed to create monitor thread for NativeProcessLinux.");
1165
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001166 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001167 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001168}
1169
1170void
1171NativeProcessLinux::Monitor::DoOperation(Operation *op)
1172{
1173 if (m_thread.EqualsThread(pthread_self())) {
1174 // If we're on the Monitor thread, we can simply execute the operation.
1175 op->Execute(m_native_process);
1176 return;
1177 }
1178
1179 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1180 Mutex::Locker lock(m_operation_mutex);
1181
1182 m_operation = op;
1183
1184 // notify the thread that an operation is ready to be processed
1185 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1186
Pavel Labath45f5cb32015-05-05 15:05:50 +00001187 WaitForAck();
1188}
1189
1190void
1191NativeProcessLinux::Monitor::Terminate()
1192{
1193 if (m_pipefd[WRITE] >= 0)
1194 {
1195 close(m_pipefd[WRITE]);
1196 m_pipefd[WRITE] = -1;
1197 }
1198 if (m_thread.IsJoinable())
1199 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00001200}
1201
Pavel Labath1107b5a2015-04-17 14:07:49 +00001202NativeProcessLinux::Monitor::~Monitor()
1203{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001204 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +00001205 if (m_pipefd[READ] >= 0)
1206 close(m_pipefd[READ]);
1207 if (m_signal_fd >= 0)
1208 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001209 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001210}
1211
1212void
1213NativeProcessLinux::Monitor::HandleSignals()
1214{
1215 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1216
1217 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1218 // all the information from waitpid(). We just need to read all the signals so that we can
1219 // sleep next time we reach select().
1220 while (true)
1221 {
1222 signalfd_siginfo info;
1223 ssize_t size = read(m_signal_fd, &info, sizeof info);
1224 if (size == -1)
1225 {
1226 if (errno == EAGAIN || errno == EWOULDBLOCK)
1227 break; // We are done.
1228 if (errno == EINTR)
1229 continue;
1230 if (log)
1231 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1232 __FUNCTION__, strerror(errno));
1233 break;
1234 }
1235 if (size != sizeof info)
1236 {
1237 // We got incomplete information structure. This should not happen, let's just log
1238 // that.
1239 if (log)
1240 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1241 "structure size is %zd, read returned %zd bytes",
1242 __FUNCTION__, sizeof info, size);
1243 break;
1244 }
1245 if (log)
1246 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1247 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1248 }
1249}
1250
1251void
1252NativeProcessLinux::Monitor::HandleWait()
1253{
1254 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1255 // Process all pending waitpid notifications.
1256 while (true)
1257 {
1258 int status = -1;
1259 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1260
1261 if (wait_pid == 0)
1262 break; // We are done.
1263
1264 if (wait_pid == -1)
1265 {
1266 if (errno == EINTR)
1267 continue;
1268
1269 if (log)
1270 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1271 __FUNCTION__, m_child_pid, strerror(errno));
1272 break;
1273 }
1274
1275 bool exited = false;
1276 int signal = 0;
1277 int exit_status = 0;
1278 const char *status_cstr = NULL;
1279 if (WIFSTOPPED(status))
1280 {
1281 signal = WSTOPSIG(status);
1282 status_cstr = "STOPPED";
1283 }
1284 else if (WIFEXITED(status))
1285 {
1286 exit_status = WEXITSTATUS(status);
1287 status_cstr = "EXITED";
1288 exited = true;
1289 }
1290 else if (WIFSIGNALED(status))
1291 {
1292 signal = WTERMSIG(status);
1293 status_cstr = "SIGNALED";
1294 if (wait_pid == abs(m_child_pid)) {
1295 exited = true;
1296 exit_status = -1;
1297 }
1298 }
1299 else
1300 status_cstr = "(\?\?\?)";
1301
1302 if (log)
1303 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1304 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1305 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1306
1307 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1308 }
1309}
1310
1311bool
1312NativeProcessLinux::Monitor::HandleCommands()
1313{
1314 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1315
1316 while (true)
1317 {
1318 char command = 0;
1319 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1320 if (size == -1)
1321 {
1322 if (errno == EAGAIN || errno == EWOULDBLOCK)
1323 return false;
1324 if (errno == EINTR)
1325 continue;
1326 if (log)
1327 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1328 return true;
1329 }
1330 if (size == 0) // end of file - write end closed
1331 {
1332 if (log)
1333 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001334 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +00001335 return true; // We are done.
1336 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001337
1338 switch (command)
1339 {
1340 case operation_command:
1341 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001342 break;
1343 case begin_block_command:
1344 ++m_operation_nesting_level;
1345 break;
1346 case end_block_command:
1347 assert(m_operation_nesting_level > 0);
1348 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001349 break;
1350 default:
1351 if (log)
1352 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1353 __FUNCTION__, command);
1354 }
Pavel Labath45f5cb32015-05-05 15:05:50 +00001355
1356 // notify calling thread that the command has been processed
1357 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001358 }
1359}
1360
1361void
1362NativeProcessLinux::Monitor::MainLoop()
1363{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001364 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1365 m_initial_operation_up.reset();
1366 m_child_pid = -getpgid(child_pid),
1367 sem_post(&m_operation_sem);
1368
Pavel Labath1107b5a2015-04-17 14:07:49 +00001369 while (true)
1370 {
1371 fd_set fds;
1372 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001373 // Only process waitpid events if we are outside of an operation block. Any pending
1374 // events will be processed after we leave the block.
1375 if (m_operation_nesting_level == 0)
1376 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001377 FD_SET(m_pipefd[READ], &fds);
1378
1379 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1380 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1381 if (r < 0)
1382 {
1383 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1384 if (log)
1385 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1386 __FUNCTION__, strerror(errno));
1387 return;
1388 }
1389
1390 if (FD_ISSET(m_pipefd[READ], &fds))
1391 {
1392 if (HandleCommands())
1393 return;
1394 }
1395
1396 if (FD_ISSET(m_signal_fd, &fds))
1397 {
1398 HandleSignals();
1399 HandleWait();
1400 }
1401 }
1402}
1403
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001404Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001405NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001406{
1407 Error error;
1408 while (sem_wait(&m_operation_sem) != 0)
1409 {
1410 if (errno == EINTR)
1411 continue;
1412
1413 error.SetErrorToErrno();
1414 return error;
1415 }
1416
1417 return m_operation_error;
1418}
1419
Pavel Labath1107b5a2015-04-17 14:07:49 +00001420void *
1421NativeProcessLinux::Monitor::RunMonitor(void *arg)
1422{
1423 static_cast<Monitor *>(arg)->MainLoop();
1424 return nullptr;
1425}
1426
1427
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001428NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001429 char const **argv,
1430 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001431 const std::string &stdin_path,
1432 const std::string &stdout_path,
1433 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001434 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001435 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001436 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +00001437 m_argv(argv),
1438 m_envp(envp),
1439 m_stdin_path(stdin_path),
1440 m_stdout_path(stdout_path),
1441 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001442 m_working_dir(working_dir),
1443 m_launch_info(launch_info)
1444{
1445}
Todd Fialaaf245d12014-06-30 21:05:18 +00001446
1447NativeProcessLinux::LaunchArgs::~LaunchArgs()
1448{ }
1449
Todd Fialaaf245d12014-06-30 21:05:18 +00001450// -----------------------------------------------------------------------------
1451// Public Static Methods
1452// -----------------------------------------------------------------------------
1453
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001454Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001455NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001456 Module *exe_module,
1457 ProcessLaunchInfo &launch_info,
1458 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001459 NativeProcessProtocolSP &native_process_sp)
1460{
1461 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1462
1463 Error error;
1464
1465 // Verify the working directory is valid if one was specified.
1466 const char* working_dir = launch_info.GetWorkingDirectory ();
1467 if (working_dir)
1468 {
1469 FileSpec working_dir_fs (working_dir, true);
1470 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1471 {
1472 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1473 return error;
1474 }
1475 }
1476
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001477 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001478
1479 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001480 std::string stdin_path;
1481 std::string stdout_path;
1482 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001483
1484 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001485 if (file_action)
1486 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001487
1488 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001489 if (file_action)
1490 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001491
1492 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001493 if (file_action)
1494 stderr_path = file_action->GetPath ();
1495
1496 if (log)
1497 {
1498 if (!stdin_path.empty ())
1499 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1500 else
1501 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1502
1503 if (!stdout_path.empty ())
1504 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1505 else
1506 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1507
1508 if (!stderr_path.empty ())
1509 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1510 else
1511 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1512 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001513
1514 // Create the NativeProcessLinux in launch mode.
1515 native_process_sp.reset (new NativeProcessLinux ());
1516
1517 if (log)
1518 {
1519 int i = 0;
1520 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1521 {
1522 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1523 ++i;
1524 }
1525 }
1526
1527 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1528 {
1529 native_process_sp.reset ();
1530 error.SetErrorStringWithFormat ("failed to register the native delegate");
1531 return error;
1532 }
1533
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001534 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001535 exe_module,
1536 launch_info.GetArguments ().GetConstArgumentVector (),
1537 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1538 stdin_path,
1539 stdout_path,
1540 stderr_path,
1541 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001542 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001543 error);
1544
1545 if (error.Fail ())
1546 {
1547 native_process_sp.reset ();
1548 if (log)
1549 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1550 return error;
1551 }
1552
1553 launch_info.SetProcessID (native_process_sp->GetID ());
1554
1555 return error;
1556}
1557
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001558Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001559NativeProcessLinux::AttachToProcess (
1560 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001561 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001562 NativeProcessProtocolSP &native_process_sp)
1563{
1564 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1565 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1566 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1567
1568 // Grab the current platform architecture. This should be Linux,
1569 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001570 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 if (!platform_sp)
1572 return Error("failed to get a valid default platform");
1573
1574 // Retrieve the architecture for the running process.
1575 ArchSpec process_arch;
1576 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1577 if (!error.Success ())
1578 return error;
1579
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001580 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001581
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001582 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001583 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001584 error.SetErrorStringWithFormat ("failed to register the native delegate");
1585 return error;
1586 }
1587
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001588 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001589 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001590 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001591
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001592 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001593 return error;
1594}
1595
1596// -----------------------------------------------------------------------------
1597// Public Instance Methods
1598// -----------------------------------------------------------------------------
1599
1600NativeProcessLinux::NativeProcessLinux () :
1601 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1602 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001603 m_supports_mem_region (eLazyBoolCalculate),
1604 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001605 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001606{
1607}
1608
1609//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001610// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1611// Refer to Monitor and Operation classes to see why this is necessary.
1612//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001613void
1614NativeProcessLinux::LaunchInferior (
1615 Module *module,
1616 const char *argv[],
1617 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001618 const std::string &stdin_path,
1619 const std::string &stdout_path,
1620 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001621 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001622 const ProcessLaunchInfo &launch_info,
1623 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001624{
1625 if (module)
1626 m_arch = module->GetArchitecture ();
1627
Chaoren Linfa03ad22015-02-03 01:50:42 +00001628 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001629
1630 std::unique_ptr<LaunchArgs> args(
1631 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001632 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001633 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001634 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001635
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001636 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001637 if (!error.Success ())
1638 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001639}
1640
1641void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001642NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001643{
1644 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1645 if (log)
1646 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1647
1648 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001649 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001650 if (!platform_sp)
1651 {
1652 if (log)
1653 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1654 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001655 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001656 }
1657
1658 // Gather info about the process.
1659 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001660 if (!platform_sp->GetProcessInfo (pid, process_info))
1661 {
1662 if (log)
1663 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1664 error.SetErrorString ("failed to get process info");
1665 return;
1666 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001667
1668 // Resolve the executable module
1669 ModuleSP exe_module_sp;
1670 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001671 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001672 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001673 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001674 if (!error.Success())
1675 return;
1676
1677 // Set the architecture to the exe architecture.
1678 m_arch = exe_module_sp->GetArchitecture();
1679 if (log)
1680 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1681
1682 m_pid = pid;
1683 SetState(eStateAttaching);
1684
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001685 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001686 if (!error.Success ())
1687 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001688}
1689
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001690void
1691NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001692{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001693 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001694}
1695
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001696::pid_t
1697NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001698{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001699 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001700
1701 const char **argv = args->m_argv;
1702 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001703 const char *working_dir = args->m_working_dir;
1704
1705 lldb_utility::PseudoTerminal terminal;
1706 const size_t err_len = 1024;
1707 char err_str[err_len];
1708 lldb::pid_t pid;
1709 NativeThreadProtocolSP thread_sp;
1710
1711 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001712
1713 // Propagate the environment if one is not supplied.
1714 if (envp == NULL || envp[0] == NULL)
1715 envp = const_cast<const char **>(environ);
1716
1717 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1718 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001719 error.SetErrorToGenericError();
1720 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1721 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001722 }
1723
1724 // Recognized child exit status codes.
1725 enum {
1726 ePtraceFailed = 1,
1727 eDupStdinFailed,
1728 eDupStdoutFailed,
1729 eDupStderrFailed,
1730 eChdirFailed,
1731 eExecFailed,
1732 eSetGidFailed
1733 };
1734
1735 // Child process.
1736 if (pid == 0)
1737 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001738 // FIXME consider opening a pipe between parent/child and have this forked child
1739 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001740
Todd Fiala75f47c32014-10-11 21:42:09 +00001741 // Start tracing this child that is about to exec.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001742 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1743 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001744 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001745
Pavel Labath493c3a12015-02-04 10:36:57 +00001746 // terminal has already dupped the tty descriptors to stdin/out/err.
1747 // This closes original fd from which they were copied (and avoids
1748 // leaking descriptors to the debugged process.
1749 terminal.CloseSlaveFileDescriptor();
1750
Todd Fialaaf245d12014-06-30 21:05:18 +00001751 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001752 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001753 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001754
1755 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001756 if (setpgid(0, 0) != 0)
1757 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001758 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001759 // Don't allow this to prevent an inferior exec.
1760 }
1761
1762 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001763 if (!args->m_stdin_path.empty ())
1764 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 exit(eDupStdinFailed);
1766
Todd Fiala75f47c32014-10-11 21:42:09 +00001767 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001768 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001769 exit(eDupStdoutFailed);
1770
Todd Fiala75f47c32014-10-11 21:42:09 +00001771 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001772 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001773 exit(eDupStderrFailed);
1774
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001775 // Close everything besides stdin, stdout, and stderr that has no file
1776 // action to avoid leaking
1777 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1778 if (!args->m_launch_info.GetFileActionForFD(fd))
1779 close(fd);
1780
Todd Fialaaf245d12014-06-30 21:05:18 +00001781 // Change working directory
1782 if (working_dir != NULL && working_dir[0])
1783 if (0 != ::chdir(working_dir))
1784 exit(eChdirFailed);
1785
Todd Fiala0bce1b62014-08-17 00:10:50 +00001786 // Disable ASLR if requested.
1787 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1788 {
1789 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1790 if (old_personality == -1)
1791 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001792 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001793 }
1794 else
1795 {
1796 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1797 if (new_personality == -1)
1798 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001799 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001800 }
1801 else
1802 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001803 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001804 }
1805 }
1806 }
1807
Todd Fiala75f47c32014-10-11 21:42:09 +00001808 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001809 execve(argv[0],
1810 const_cast<char *const *>(argv),
1811 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001812
1813 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001814 exit(eExecFailed);
1815 }
1816
Todd Fiala75f47c32014-10-11 21:42:09 +00001817 //
1818 // This is the parent code here.
1819 //
1820 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1821
Todd Fialaaf245d12014-06-30 21:05:18 +00001822 // Wait for the child process to trap on its call to execve.
1823 ::pid_t wpid;
1824 int status;
1825 if ((wpid = waitpid(pid, &status, 0)) < 0)
1826 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001827 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001828 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001829 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1830 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001831
1832 // Mark the inferior as invalid.
1833 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001834 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001835
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001836 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001837 }
1838 else if (WIFEXITED(status))
1839 {
1840 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001841 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001842 switch (WEXITSTATUS(status))
1843 {
1844 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001845 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 break;
1847 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001848 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001849 break;
1850 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001851 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001852 break;
1853 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001854 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001855 break;
1856 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001857 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001858 break;
1859 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001860 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001861 break;
1862 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001863 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001864 break;
1865 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001866 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001867 break;
1868 }
1869
1870 if (log)
1871 {
1872 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1873 __FUNCTION__,
1874 WEXITSTATUS(status));
1875 }
1876
1877 // Mark the inferior as invalid.
1878 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001879 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001880
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001881 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001882 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001883 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001884 "Could not sync with inferior process.");
1885
1886 if (log)
1887 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1888
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001889 error = SetDefaultPtraceOpts(pid);
1890 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001891 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001892 if (log)
1893 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001894 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001895
1896 // Mark the inferior as invalid.
1897 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001898 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001899
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001900 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001901 }
1902
1903 // Release the master terminal descriptor and pass it off to the
1904 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001905 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1906 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001907
1908 // Set the terminal fd to be in non blocking mode (it simplifies the
1909 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1910 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001911 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1912 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001913 {
1914 if (log)
1915 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001916 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001917
1918 // Mark the inferior as invalid.
1919 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001920 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001921
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001922 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001923 }
1924
1925 if (log)
1926 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1927
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001928 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001929 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001930 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001931 NotifyThreadCreate(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001932
1933 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001934 SetCurrentThreadID (thread_sp->GetID ());
1935 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001936
Todd Fialaaf245d12014-06-30 21:05:18 +00001937 if (log)
1938 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001939 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001940 {
1941 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1942 }
1943 else
1944 {
1945 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001946 __FUNCTION__, error.AsCString ());
1947 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001948 }
1949 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001950 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001951}
1952
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001953::pid_t
1954NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001955{
Todd Fialaaf245d12014-06-30 21:05:18 +00001956 lldb::ThreadSP inferior;
1957 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1958
1959 // Use a map to keep track of the threads which we have attached/need to attach.
1960 Host::TidMap tids_to_attach;
1961 if (pid <= 1)
1962 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001963 error.SetErrorToGenericError();
1964 error.SetErrorString("Attaching to process 1 is not allowed.");
1965 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001966 }
1967
1968 while (Host::FindProcessThreads(pid, tids_to_attach))
1969 {
1970 for (Host::TidMap::iterator it = tids_to_attach.begin();
1971 it != tids_to_attach.end();)
1972 {
1973 if (it->second == false)
1974 {
1975 lldb::tid_t tid = it->first;
1976
1977 // Attach to the requested process.
1978 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001979 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
1980 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001981 {
1982 // No such thread. The thread may have exited.
1983 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001984 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001985 {
1986 it = tids_to_attach.erase(it);
1987 continue;
1988 }
1989 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001990 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001991 }
1992
1993 int status;
1994 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1995 // At this point we should have a thread stopped if waitpid succeeds.
1996 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1997 {
1998 // No such thread. The thread may have exited.
1999 // More error handling may be needed.
2000 if (errno == ESRCH)
2001 {
2002 it = tids_to_attach.erase(it);
2003 continue;
2004 }
2005 else
2006 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002007 error.SetErrorToErrno();
2008 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002009 }
2010 }
2011
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002012 error = SetDefaultPtraceOpts(tid);
2013 if (error.Fail())
2014 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002015
2016 if (log)
2017 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2018
2019 it->second = true;
2020
2021 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002022 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00002023 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002024
2025 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002026 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002027 NotifyThreadCreate(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002028 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002029 }
2030
2031 // move the loop forward
2032 ++it;
2033 }
2034 }
2035
2036 if (tids_to_attach.size() > 0)
2037 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002038 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002039 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002040 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002041 }
2042 else
2043 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002044 error.SetErrorToGenericError();
2045 error.SetErrorString("No such process.");
2046 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002047 }
2048
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002049 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002050}
2051
Chaoren Lin97ccc292015-02-03 01:51:12 +00002052Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002053NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2054{
2055 long ptrace_opts = 0;
2056
2057 // Have the child raise an event on exit. This is used to keep the child in
2058 // limbo until it is destroyed.
2059 ptrace_opts |= PTRACE_O_TRACEEXIT;
2060
2061 // Have the tracer trace threads which spawn in the inferior process.
2062 // TODO: if we want to support tracing the inferiors' child, add the
2063 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2064 ptrace_opts |= PTRACE_O_TRACECLONE;
2065
2066 // Have the tracer notify us before execve returns
2067 // (needed to disable legacy SIGTRAP generation)
2068 ptrace_opts |= PTRACE_O_TRACEEXEC;
2069
Chaoren Lin97ccc292015-02-03 01:51:12 +00002070 Error error;
2071 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2072 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002073}
2074
2075static ExitType convert_pid_status_to_exit_type (int status)
2076{
2077 if (WIFEXITED (status))
2078 return ExitType::eExitTypeExit;
2079 else if (WIFSIGNALED (status))
2080 return ExitType::eExitTypeSignal;
2081 else if (WIFSTOPPED (status))
2082 return ExitType::eExitTypeStop;
2083 else
2084 {
2085 // We don't know what this is.
2086 return ExitType::eExitTypeInvalid;
2087 }
2088}
2089
2090static int convert_pid_status_to_return_code (int status)
2091{
2092 if (WIFEXITED (status))
2093 return WEXITSTATUS (status);
2094 else if (WIFSIGNALED (status))
2095 return WTERMSIG (status);
2096 else if (WIFSTOPPED (status))
2097 return WSTOPSIG (status);
2098 else
2099 {
2100 // We don't know what this is.
2101 return ExitType::eExitTypeInvalid;
2102 }
2103}
2104
Pavel Labath1107b5a2015-04-17 14:07:49 +00002105// Handles all waitpid events from the inferior process.
2106void
2107NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00002108 bool exited,
2109 int signal,
2110 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00002111{
2112 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2113
Todd Fialaaf245d12014-06-30 21:05:18 +00002114 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002115 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002116
2117 // Handle when the thread exits.
2118 if (exited)
2119 {
2120 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002121 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 +00002122
2123 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002124 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002125
Chaoren Linfa03ad22015-02-03 01:50:42 +00002126 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002127 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002128
Todd Fialaaf245d12014-06-30 21:05:18 +00002129 if (is_main_thread)
2130 {
2131 // We only set the exit status and notify the delegate if we haven't already set the process
2132 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2133 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002134 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00002135 if (!already_notified)
2136 {
2137 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002138 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 +00002139 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002140 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002141
2142 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002143 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002144 }
2145 else
2146 {
2147 if (log)
2148 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2149 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002150 }
2151 else
2152 {
2153 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2154 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2155 // and we would have done an all-stop then.
2156 if (log)
2157 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 +00002158 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00002159 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00002160 }
2161
2162 // Get details on the signal raised.
2163 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00002164 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00002165 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002166 {
2167 // We have retrieved the signal info. Dispatch appropriately.
2168 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002169 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002170 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00002171 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002172 }
2173 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002174 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002175 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002176 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002177 // This is a group stop reception for this tid.
2178 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002179 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002180 NotifyThreadStop (pid, false);
Todd Fialaaf245d12014-06-30 21:05:18 +00002181 }
2182 else
2183 {
2184 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2185
2186 // A return value of ESRCH means the thread/process is no longer on the system,
2187 // so it was killed somehow outside of our control. Either way, we can't do anything
2188 // with it anymore.
2189
Todd Fialaaf245d12014-06-30 21:05:18 +00002190 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002191 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002192
Chaoren Linfa03ad22015-02-03 01:50:42 +00002193 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002194 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002195
Todd Fialaaf245d12014-06-30 21:05:18 +00002196 if (log)
2197 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002198 __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 +00002199
2200 if (is_main_thread)
2201 {
2202 // Notify the delegate - our process is not available but appears to have been killed outside
2203 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00002204 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2205 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002206 }
2207 else
2208 {
2209 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2210 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002211 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 +00002212 }
2213 }
2214 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002215}
2216
2217void
Pavel Labath426bdf82015-04-28 07:51:52 +00002218NativeProcessLinux::WaitForNewThread(::pid_t tid)
2219{
2220 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2221
2222 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2223
2224 if (new_thread_sp)
2225 {
2226 // We are already tracking the thread - we got the event on the new thread (see
2227 // MonitorSignal) before this one. We are done.
2228 return;
2229 }
2230
2231 // The thread is not tracked yet, let's wait for it to appear.
2232 int status = -1;
2233 ::pid_t wait_pid;
2234 do
2235 {
2236 if (log)
2237 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2238 wait_pid = waitpid(tid, &status, __WALL);
2239 }
2240 while (wait_pid == -1 && errno == EINTR);
2241 // Since we are waiting on a specific tid, this must be the creation event. But let's do
2242 // some checks just in case.
2243 if (wait_pid != tid) {
2244 if (log)
2245 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2246 // The only way I know of this could happen is if the whole process was
2247 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2248 return;
2249 }
2250 if (WIFEXITED(status))
2251 {
2252 if (log)
2253 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2254 // Also a very improbable event.
2255 return;
2256 }
2257
2258 siginfo_t info;
2259 Error error = GetSignalInfo(tid, &info);
2260 if (error.Fail())
2261 {
2262 if (log)
2263 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2264 return;
2265 }
2266
2267 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2268 {
2269 // We should be getting a thread creation signal here, but we received something
2270 // else. There isn't much we can do about it now, so we will just log that. Since the
2271 // thread is alive and we are receiving events from it, we shall pretend that it was
2272 // created properly.
2273 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);
2274 }
2275
2276 if (log)
2277 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2278 __FUNCTION__, GetID (), tid);
2279
2280 new_thread_sp = AddThread(tid);
2281 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2282 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002283 NotifyThreadCreate(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00002284}
2285
2286void
Todd Fialaaf245d12014-06-30 21:05:18 +00002287NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2288{
2289 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2290 const bool is_main_thread = (pid == GetID ());
2291
2292 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2293 if (!info)
2294 return;
2295
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002296 Mutex::Locker locker (m_threads_mutex);
2297
Todd Fialaaf245d12014-06-30 21:05:18 +00002298 // See if we can find a thread for this signal.
2299 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2300 if (!thread_sp)
2301 {
2302 if (log)
2303 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2304 }
2305
2306 switch (info->si_code)
2307 {
2308 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2309 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2310 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2311
2312 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2313 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002314 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00002315 // creation.
2316 // We don't want to do anything with the parent thread so we just resume it. In case we
2317 // want to implement "break on thread creation" functionality, we would need to stop
2318 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00002319
Pavel Labath426bdf82015-04-28 07:51:52 +00002320 unsigned long event_message = 0;
2321 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002322 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002323 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002324 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 +00002325 } else
2326 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002327
Pavel Labath5fd24c62015-04-23 09:04:35 +00002328 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002329 break;
2330 }
2331
2332 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002333 {
2334 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002335 if (log)
2336 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002337
Chaoren Linfa03ad22015-02-03 01:50:42 +00002338 // The thread state coordinator needs to reset due to the exec.
Pavel Labathc0765592015-05-06 10:46:34 +00002339 ResetForExec ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002340
2341 // 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 +00002342 if (log)
2343 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2344
2345 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002346 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002347 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2348 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002349 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002350 main_thread_sp = thread_sp;
2351 if (log)
2352 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002353 }
2354 else
2355 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002356 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002357 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002358 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002359 }
2360 }
2361
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002362 m_threads.clear ();
2363
2364 if (main_thread_sp)
2365 {
2366 m_threads.push_back (main_thread_sp);
2367 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002368 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002369 }
2370 else
2371 {
2372 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2373 if (log)
2374 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2375 }
2376
Chaoren Linfa03ad22015-02-03 01:50:42 +00002377 // Tell coordinator about about the "new" (since exec) stopped main thread.
2378 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002379 NotifyThreadCreate(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002380
2381 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2382 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002383 // Let our delegate know we have just exec'd.
2384 NotifyDidExec ();
2385
2386 // If we have a main thread, indicate we are stopped.
2387 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002388
2389 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002390 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002391
Todd Fialaaf245d12014-06-30 21:05:18 +00002392 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002393 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002394
2395 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2396 {
2397 // The inferior process or one of its threads is about to exit.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002398 if (! thread_sp)
2399 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00002400
2401 // This thread is currently stopped. It's not actually dead yet, just about to be.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002402 NotifyThreadStop (pid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002403 // The actual stop reason does not matter much, as we are going to resume the thread a
2404 // few lines down. If we ever want to report this state to the debugger, then we should
2405 // invent a new stop reason.
2406 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002407
Todd Fialaaf245d12014-06-30 21:05:18 +00002408 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002409 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002410 data = -1;
2411
2412 if (log)
2413 {
2414 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2415 __FUNCTION__,
2416 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2417 pid,
2418 is_main_thread ? "is main thread" : "not main thread");
2419 }
2420
Todd Fialaaf245d12014-06-30 21:05:18 +00002421 if (is_main_thread)
2422 {
2423 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002424 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002425
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002426 const int signo = static_cast<int> (data);
Pavel Labathc0765592015-05-06 10:46:34 +00002427 RequestThreadResume (pid,
2428 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2429 {
2430 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2431 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002432 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002433
2434 break;
2435 }
2436
2437 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002438 case TRAP_TRACE: // We receive this on single stepping.
2439 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002440 if (thread_sp)
2441 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002442 // If a watchpoint was hit, report it
2443 uint32_t wp_index;
2444 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2445 if (error.Fail() && log)
2446 log->Printf("NativeProcessLinux::%s() "
2447 "received error while checking for watchpoint hits, "
2448 "pid = %" PRIu64 " error = %s",
2449 __FUNCTION__, pid, error.AsCString());
2450 if (wp_index != LLDB_INVALID_INDEX32)
2451 {
2452 MonitorWatchpoint(pid, thread_sp, wp_index);
2453 break;
2454 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002455 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002456 // Otherwise, report step over
2457 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002458 break;
2459
2460 case SI_KERNEL:
2461 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002462 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002463 break;
2464
2465 case SIGTRAP:
2466 case (SIGTRAP | 0x80):
2467 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002468 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2469
2470 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002471 NotifyThreadStop (pid, false);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002472 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002473 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002474
2475
Todd Fialaaf245d12014-06-30 21:05:18 +00002476 // Ignore these signals until we know more about them.
Pavel Labathc0765592015-05-06 10:46:34 +00002477 RequestThreadResume (pid,
2478 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2479 {
2480 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2481 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002482 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002483 break;
2484
2485 default:
2486 assert(false && "Unexpected SIGTRAP code!");
2487 if (log)
2488 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)));
2489 break;
2490
2491 }
2492}
2493
2494void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002495NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2496{
2497 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2498 if (log)
2499 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2500 __FUNCTION__, pid);
2501
2502 if (thread_sp)
2503 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2504
2505 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002506 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002507
2508 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2509 // This would have already happened at the time the Resume() with step operation was signaled.
2510 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2511 // once all running threads have checked in as stopped.
2512 SetCurrentThreadID(pid);
2513 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00002514 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002515}
2516
2517void
2518NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2519{
2520 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2521 if (log)
2522 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2523 __FUNCTION__, pid);
2524
2525 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002526 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002527
2528 // Mark the thread as stopped at breakpoint.
2529 if (thread_sp)
2530 {
2531 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2532 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2533 if (error.Fail())
2534 if (log)
2535 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2536 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002537
2538 auto it = m_threads_stepping_with_breakpoint.find(pid);
2539 if (it != m_threads_stepping_with_breakpoint.end())
2540 {
2541 Error error = RemoveBreakpoint (it->second);
2542 if (error.Fail())
2543 if (log)
2544 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2545 __FUNCTION__, pid, error.AsCString());
2546
2547 m_threads_stepping_with_breakpoint.erase(it);
2548 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2549 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002550 }
2551 else
2552 if (log)
2553 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2554 "warning, cannot process software breakpoint since no thread metadata",
2555 __FUNCTION__, pid);
2556
2557
2558 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002559 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002560}
2561
2562void
2563NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2564{
2565 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2566 if (log)
2567 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2568 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2569 __FUNCTION__, pid, wp_index);
2570
2571 // This thread is currently stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002572 NotifyThreadStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002573
2574 // Mark the thread as stopped at watchpoint.
2575 // The address is at (lldb::addr_t)info->si_addr if we need it.
2576 lldbassert(thread_sp && "thread_sp cannot be NULL");
2577 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2578
2579 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002580 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002581}
2582
2583void
Todd Fialaaf245d12014-06-30 21:05:18 +00002584NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2585{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002586 assert (info && "null info");
2587 if (!info)
2588 return;
2589
2590 const int signo = info->si_signo;
2591 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002592
2593 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2594
2595 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2596 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2597 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2598 //
2599 // IOW, user generated signals never generate what we consider to be a
2600 // "crash".
2601 //
2602 // Similarly, ACK signals generated by this monitor.
2603
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002604 Mutex::Locker locker (m_threads_mutex);
2605
Todd Fialaaf245d12014-06-30 21:05:18 +00002606 // See if we can find a thread for this signal.
2607 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2608 if (!thread_sp)
2609 {
2610 if (log)
2611 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2612 }
2613
2614 // Handle the signal.
2615 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2616 {
2617 if (log)
2618 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2619 __FUNCTION__,
2620 GetUnixSignals ().GetSignalAsCString (signo),
2621 signo,
2622 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2623 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002624 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002625 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002626 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002627
Todd Fiala58a2f662014-08-12 17:02:07 +00002628 // Check for new thread notification.
2629 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2630 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002631 // A new thread creation is being signaled. This is one of two parts that come in
2632 // a non-deterministic order. This code handles the case where the new thread event comes
2633 // before the event on the parent thread. For the opposite case see code in
2634 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002635 if (log)
2636 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2637 __FUNCTION__, GetID (), pid);
2638
Pavel Labath5fd24c62015-04-23 09:04:35 +00002639 thread_sp = AddThread(pid);
2640 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2641 // We can now resume the newly created thread.
2642 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2643 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002644 NotifyThreadCreate(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002645 // Done handling.
2646 return;
2647 }
2648
2649 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002650 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002651 {
2652 // This is a tgkill()-based stop.
2653 if (thread_sp)
2654 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002655 if (log)
2656 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2657 __FUNCTION__,
2658 GetID (),
2659 pid);
2660
Chaoren Linaab58632015-02-03 01:50:57 +00002661 // Check that we're not already marked with a stop reason.
2662 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2663 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2664 // and that, without an intervening resume, we received another stop. It is more likely
2665 // that we are missing the marking of a run state somewhere if we find that the thread was
2666 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002667 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2668 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002669
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002670 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002671 if (!StateIsStoppedState (thread_state, false))
2672 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002673 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2674 // Generally, these are not important stops and we don't want to report them as
2675 // they are just used to stop other threads when one thread (the one with the
2676 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2677 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2678 // leave the signal intact if this is the thread that was chosen as the
2679 // triggering thread.
2680 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2681 linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2682 else
2683 linux_thread_sp->SetStoppedBySignal(0);
2684
Chaoren Linaab58632015-02-03 01:50:57 +00002685 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002686 NotifyThreadStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002687 }
2688 else
2689 {
2690 if (log)
2691 {
2692 // Retrieve the signal name if the thread was stopped by a signal.
2693 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002694 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002695 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2696 if (!signal_name)
2697 signal_name = "<no-signal-name>";
2698
2699 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",
2700 __FUNCTION__,
2701 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002702 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002703 StateAsCString (thread_state),
2704 stop_signo,
2705 signal_name);
2706 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002707 // Tell the thread state coordinator about the stop.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002708 NotifyThreadStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002709 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002710 }
2711
2712 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002713 return;
2714 }
2715
2716 if (log)
2717 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2718
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002719 // This thread is stopped.
Pavel Labath5eb721e2015-05-07 08:30:31 +00002720 NotifyThreadStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002721
Todd Fialaaf245d12014-06-30 21:05:18 +00002722 switch (signo)
2723 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002724 case SIGSTOP:
2725 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002726 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002727 if (log)
2728 {
2729 if (is_from_llgs)
2730 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2731 else
2732 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2733 }
2734
Chaoren Linfa03ad22015-02-03 01:50:42 +00002735 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2736 // This thread will get stopped again as part of the group-stop completion.
Pavel Labathc0765592015-05-06 10:46:34 +00002737 RequestThreadResume (pid,
2738 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2739 {
2740 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2741 // Pass this signal number on to the inferior to handle.
2742 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
Pavel Labath5eb721e2015-05-07 08:30:31 +00002743 });
Todd Fiala511e5cd2014-09-11 23:29:14 +00002744 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002745 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002746 case SIGSEGV:
2747 case SIGILL:
2748 case SIGFPE:
2749 case SIGBUS:
2750 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002751 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002752 break;
2753 default:
2754 // This is just a pre-signal-delivery notification of the incoming signal.
2755 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002756 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002757
2758 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002759 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002760
2761 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002762 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002763}
2764
Tamas Berghammere7708682015-04-22 10:00:23 +00002765namespace {
2766
2767struct EmulatorBaton
2768{
2769 NativeProcessLinux* m_process;
2770 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002771
Pavel Labath6648fcc2015-04-27 09:21:14 +00002772 // eRegisterKindDWARF -> RegsiterValue
2773 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2774
2775 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002776 m_process(process), m_reg_context(reg_context) {}
2777};
2778
2779} // anonymous namespace
2780
2781static size_t
2782ReadMemoryCallback (EmulateInstruction *instruction,
2783 void *baton,
2784 const EmulateInstruction::Context &context,
2785 lldb::addr_t addr,
2786 void *dst,
2787 size_t length)
2788{
2789 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2790
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002791 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002792 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2793 return bytes_read;
2794}
2795
2796static bool
2797ReadRegisterCallback (EmulateInstruction *instruction,
2798 void *baton,
2799 const RegisterInfo *reg_info,
2800 RegisterValue &reg_value)
2801{
2802 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2803
Pavel Labath6648fcc2015-04-27 09:21:14 +00002804 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2805 if (it != emulator_baton->m_register_values.end())
2806 {
2807 reg_value = it->second;
2808 return true;
2809 }
2810
Tamas Berghammere7708682015-04-22 10:00:23 +00002811 // The emulator only fill in the dwarf regsiter numbers (and in some case
2812 // the generic register numbers). Get the full register info from the
2813 // register context based on the dwarf register numbers.
2814 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2815 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2816
2817 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002818 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002819 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002820
Pavel Labath6648fcc2015-04-27 09:21:14 +00002821 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002822}
2823
2824static bool
2825WriteRegisterCallback (EmulateInstruction *instruction,
2826 void *baton,
2827 const EmulateInstruction::Context &context,
2828 const RegisterInfo *reg_info,
2829 const RegisterValue &reg_value)
2830{
2831 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002832 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002833 return true;
2834}
2835
2836static size_t
2837WriteMemoryCallback (EmulateInstruction *instruction,
2838 void *baton,
2839 const EmulateInstruction::Context &context,
2840 lldb::addr_t addr,
2841 const void *dst,
2842 size_t length)
2843{
2844 return length;
2845}
2846
2847static lldb::addr_t
2848ReadFlags (NativeRegisterContext* regsiter_context)
2849{
2850 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2851 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2852 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2853}
2854
2855Error
2856NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2857{
2858 Error error;
2859 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2860
2861 std::unique_ptr<EmulateInstruction> emulator_ap(
2862 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2863
2864 if (emulator_ap == nullptr)
2865 return Error("Instruction emulator not found!");
2866
2867 EmulatorBaton baton(this, register_context_sp.get());
2868 emulator_ap->SetBaton(&baton);
2869 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2870 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2871 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2872 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2873
2874 if (!emulator_ap->ReadInstruction())
2875 return Error("Read instruction failed!");
2876
Pavel Labath6648fcc2015-04-27 09:21:14 +00002877 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2878
2879 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2880 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2881
2882 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2883 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2884
Tamas Berghammere7708682015-04-22 10:00:23 +00002885 lldb::addr_t next_pc;
2886 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002887 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002888 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002889 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2890 next_pc = pc_it->second.GetAsUInt64();
2891
2892 if (flags_it != baton.m_register_values.end())
2893 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002894 else
2895 next_flags = ReadFlags (register_context_sp.get());
2896 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002897 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002898 {
2899 // Emulate instruction failed and it haven't changed PC. Advance PC
2900 // with the size of the current opcode because the emulation of all
2901 // PC modifying instruction should be successful. The failure most
2902 // likely caused by a not supported instruction which don't modify PC.
2903 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2904 next_flags = ReadFlags (register_context_sp.get());
2905 }
2906 else
2907 {
2908 // The instruction emulation failed after it modified the PC. It is an
2909 // unknown error where we can't continue because the next instruction is
2910 // modifying the PC but we don't know how.
2911 return Error ("Instruction emulation failed unexpectedly.");
2912 }
2913
2914 if (m_arch.GetMachine() == llvm::Triple::arm)
2915 {
2916 if (next_flags & 0x20)
2917 {
2918 // Thumb mode
2919 error = SetSoftwareBreakpoint(next_pc, 2);
2920 }
2921 else
2922 {
2923 // Arm mode
2924 error = SetSoftwareBreakpoint(next_pc, 4);
2925 }
2926 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002927 else if (m_arch.GetMachine() == llvm::Triple::mips64
2928 || m_arch.GetMachine() == llvm::Triple::mips64el)
2929 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002930 else
2931 {
2932 // No size hint is given for the next breakpoint
2933 error = SetSoftwareBreakpoint(next_pc, 0);
2934 }
2935
Tamas Berghammere7708682015-04-22 10:00:23 +00002936 if (error.Fail())
2937 return error;
2938
2939 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2940
2941 return Error();
2942}
2943
2944bool
2945NativeProcessLinux::SupportHardwareSingleStepping() const
2946{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002947 if (m_arch.GetMachine() == llvm::Triple::arm
2948 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2949 return false;
2950 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002951}
2952
Todd Fialaaf245d12014-06-30 21:05:18 +00002953Error
2954NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2955{
Todd Fialaaf245d12014-06-30 21:05:18 +00002956 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2957 if (log)
2958 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2959
Chaoren Lin03f12d62015-02-03 01:50:49 +00002960 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2961 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00002962 int deferred_signo = 0;
2963 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002964 bool stepping = false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002965 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002966
Pavel Labath45f5cb32015-05-05 15:05:50 +00002967 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002968 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002969
Tamas Berghammere7708682015-04-22 10:00:23 +00002970 if (software_single_step)
2971 {
2972 for (auto thread_sp : m_threads)
2973 {
2974 assert (thread_sp && "thread list should not contain NULL threads");
2975
2976 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2977 if (action == nullptr)
2978 continue;
2979
2980 if (action->state == eStateStepping)
2981 {
2982 Error error = SetupSoftwareSingleStepping(thread_sp);
2983 if (error.Fail())
2984 return error;
2985 }
2986 }
2987 }
2988
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002989 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002990 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002991 assert (thread_sp && "thread list should not contain NULL threads");
2992
2993 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2994
2995 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002996 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002997 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002998 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2999 __FUNCTION__, GetID (), thread_sp->GetID ());
3000 continue;
3001 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003002
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003003 if (log)
3004 {
3005 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3006 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3007 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003008
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003009 switch (action->state)
3010 {
3011 case eStateRunning:
3012 {
3013 // Run the thread, possibly feeding it the signal.
3014 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003015 RequestThreadResumeAsNeeded (thread_sp->GetID (),
3016 [=](lldb::tid_t tid_to_resume, bool supress_signal)
3017 {
3018 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3019 // Pass this signal number on to the inferior to handle.
3020 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3021 if (resume_result.Success())
3022 SetState(eStateRunning, true);
3023 return resume_result;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003024 });
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003025 break;
3026 }
3027
3028 case eStateStepping:
3029 {
3030 // Request the step.
3031 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003032 RequestThreadResume (thread_sp->GetID (),
3033 [=](lldb::tid_t tid_to_step, bool supress_signal)
3034 {
3035 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00003036
Pavel Labathc0765592015-05-06 10:46:34 +00003037 Error step_result;
3038 if (software_single_step)
3039 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3040 else
3041 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00003042
Pavel Labathc0765592015-05-06 10:46:34 +00003043 assert (step_result.Success() && "SingleStep() failed");
3044 if (step_result.Success())
3045 SetState(eStateStepping, true);
3046 return step_result;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003047 });
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003048 stepping = true;
3049 break;
3050 }
3051
3052 case eStateSuspended:
3053 case eStateStopped:
3054 // if we haven't chosen a deferred signal tid yet, use this one.
3055 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00003056 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003057 deferred_signal_tid = thread_sp->GetID ();
3058 deferred_signal_thread_sp = thread_sp;
3059 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00003060 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003061 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00003062
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003063 default:
3064 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3065 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003066 }
3067 }
3068
Chaoren Linfa03ad22015-02-03 01:50:42 +00003069 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
3070 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003071 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
3072 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Pavel Labathed89c7f2015-05-06 12:22:37 +00003073 StopRunningThreadsWithSkipTID(deferred_signal_tid, deferred_signal_skip_tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00003074
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003075 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00003076}
3077
3078Error
3079NativeProcessLinux::Halt ()
3080{
3081 Error error;
3082
Todd Fialaaf245d12014-06-30 21:05:18 +00003083 if (kill (GetID (), SIGSTOP) != 0)
3084 error.SetErrorToErrno ();
3085
3086 return error;
3087}
3088
3089Error
3090NativeProcessLinux::Detach ()
3091{
3092 Error error;
3093
3094 // Tell ptrace to detach from the process.
3095 if (GetID () != LLDB_INVALID_PROCESS_ID)
3096 error = Detach (GetID ());
3097
3098 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00003099 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00003100
3101 // No error.
3102 return error;
3103}
3104
3105Error
3106NativeProcessLinux::Signal (int signo)
3107{
3108 Error error;
3109
3110 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3111 if (log)
3112 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3113 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3114
3115 if (kill(GetID(), signo))
3116 error.SetErrorToErrno();
3117
3118 return error;
3119}
3120
3121Error
Chaoren Line9547b82015-02-03 01:51:00 +00003122NativeProcessLinux::Interrupt ()
3123{
3124 // Pick a running thread (or if none, a not-dead stopped thread) as
3125 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00003126 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3127
3128 NativeThreadProtocolSP running_thread_sp;
3129 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003130
3131 if (log)
3132 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3133
Pavel Labath45f5cb32015-05-05 15:05:50 +00003134 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003135 Mutex::Locker locker (m_threads_mutex);
3136
3137 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00003138 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003139 // The thread shouldn't be null but lets just cover that here.
3140 if (!thread_sp)
3141 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00003142
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003143 // If we have a running or stepping thread, we'll call that the
3144 // target of the interrupt.
3145 const auto thread_state = thread_sp->GetState ();
3146 if (thread_state == eStateRunning ||
3147 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00003148 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003149 running_thread_sp = thread_sp;
3150 break;
3151 }
3152 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3153 {
3154 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
3155 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00003156 }
3157 }
3158
3159 if (!running_thread_sp && !stopped_thread_sp)
3160 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003161 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00003162 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00003163 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003164
Chaoren Line9547b82015-02-03 01:51:00 +00003165 return error;
3166 }
3167
3168 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3169
3170 if (log)
3171 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3172 __FUNCTION__,
3173 GetID (),
3174 running_thread_sp ? "running" : "stopped",
3175 deferred_signal_thread_sp->GetID ());
3176
Pavel Labathed89c7f2015-05-06 12:22:37 +00003177 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00003178
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003179 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00003180}
3181
3182Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003183NativeProcessLinux::Kill ()
3184{
3185 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3186 if (log)
3187 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3188
3189 Error error;
3190
3191 switch (m_state)
3192 {
3193 case StateType::eStateInvalid:
3194 case StateType::eStateExited:
3195 case StateType::eStateCrashed:
3196 case StateType::eStateDetached:
3197 case StateType::eStateUnloaded:
3198 // Nothing to do - the process is already dead.
3199 if (log)
3200 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3201 return error;
3202
3203 case StateType::eStateConnected:
3204 case StateType::eStateAttaching:
3205 case StateType::eStateLaunching:
3206 case StateType::eStateStopped:
3207 case StateType::eStateRunning:
3208 case StateType::eStateStepping:
3209 case StateType::eStateSuspended:
3210 // We can try to kill a process in these states.
3211 break;
3212 }
3213
3214 if (kill (GetID (), SIGKILL) != 0)
3215 {
3216 error.SetErrorToErrno ();
3217 return error;
3218 }
3219
3220 return error;
3221}
3222
3223static Error
3224ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3225{
3226 memory_region_info.Clear();
3227
3228 StringExtractor line_extractor (maps_line.c_str ());
3229
3230 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
3231 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
3232
3233 // Parse out the starting address
3234 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3235
3236 // Parse out hyphen separating start and end address from range.
3237 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3238 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3239
3240 // Parse out the ending address
3241 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3242
3243 // Parse out the space after the address.
3244 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3245 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3246
3247 // Save the range.
3248 memory_region_info.GetRange ().SetRangeBase (start_address);
3249 memory_region_info.GetRange ().SetRangeEnd (end_address);
3250
3251 // Parse out each permission entry.
3252 if (line_extractor.GetBytesLeft () < 4)
3253 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3254
3255 // Handle read permission.
3256 const char read_perm_char = line_extractor.GetChar ();
3257 if (read_perm_char == 'r')
3258 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3259 else
3260 {
3261 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3262 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3263 }
3264
3265 // Handle write permission.
3266 const char write_perm_char = line_extractor.GetChar ();
3267 if (write_perm_char == 'w')
3268 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3269 else
3270 {
3271 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3272 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3273 }
3274
3275 // Handle execute permission.
3276 const char exec_perm_char = line_extractor.GetChar ();
3277 if (exec_perm_char == 'x')
3278 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3279 else
3280 {
3281 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3282 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3283 }
3284
3285 return Error ();
3286}
3287
3288Error
3289NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3290{
3291 // FIXME review that the final memory region returned extends to the end of the virtual address space,
3292 // with no perms if it is not mapped.
3293
3294 // Use an approach that reads memory regions from /proc/{pid}/maps.
3295 // Assume proc maps entries are in ascending order.
3296 // FIXME assert if we find differently.
3297 Mutex::Locker locker (m_mem_region_cache_mutex);
3298
3299 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3300 Error error;
3301
3302 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3303 {
3304 // We're done.
3305 error.SetErrorString ("unsupported");
3306 return error;
3307 }
3308
3309 // If our cache is empty, pull the latest. There should always be at least one memory region
3310 // if memory region handling is supported.
3311 if (m_mem_region_cache.empty ())
3312 {
3313 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3314 [&] (const std::string &line) -> bool
3315 {
3316 MemoryRegionInfo info;
3317 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3318 if (parse_error.Success ())
3319 {
3320 m_mem_region_cache.push_back (info);
3321 return true;
3322 }
3323 else
3324 {
3325 if (log)
3326 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3327 return false;
3328 }
3329 });
3330
3331 // If we had an error, we'll mark unsupported.
3332 if (error.Fail ())
3333 {
3334 m_supports_mem_region = LazyBool::eLazyBoolNo;
3335 return error;
3336 }
3337 else if (m_mem_region_cache.empty ())
3338 {
3339 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3340 // is supported. Assume we don't support map entries via procfs.
3341 if (log)
3342 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3343 m_supports_mem_region = LazyBool::eLazyBoolNo;
3344 error.SetErrorString ("not supported");
3345 return error;
3346 }
3347
3348 if (log)
3349 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3350
3351 // We support memory retrieval, remember that.
3352 m_supports_mem_region = LazyBool::eLazyBoolYes;
3353 }
3354 else
3355 {
3356 if (log)
3357 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3358 }
3359
3360 lldb::addr_t prev_base_address = 0;
3361
3362 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3363 // There can be a ton of regions on pthreads apps with lots of threads.
3364 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3365 {
3366 MemoryRegionInfo &proc_entry_info = *it;
3367
3368 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3369 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3370 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3371
3372 // If the target address comes before this entry, indicate distance to next region.
3373 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3374 {
3375 range_info.GetRange ().SetRangeBase (load_addr);
3376 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3377 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3378 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3379 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3380
3381 return error;
3382 }
3383 else if (proc_entry_info.GetRange ().Contains (load_addr))
3384 {
3385 // The target address is within the memory region we're processing here.
3386 range_info = proc_entry_info;
3387 return error;
3388 }
3389
3390 // The target memory address comes somewhere after the region we just parsed.
3391 }
3392
3393 // If we made it here, we didn't find an entry that contained the given address.
3394 error.SetErrorString ("address comes after final region");
3395
3396 if (log)
3397 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3398
3399 return error;
3400}
3401
3402void
3403NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3404{
3405 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3406 if (log)
3407 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3408
3409 {
3410 Mutex::Locker locker (m_mem_region_cache_mutex);
3411 if (log)
3412 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3413 m_mem_region_cache.clear ();
3414 }
3415}
3416
3417Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003418NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00003419{
3420 // FIXME implementing this requires the equivalent of
3421 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3422 // functional ThreadPlans working with Native*Protocol.
3423#if 1
3424 return Error ("not implemented yet");
3425#else
3426 addr = LLDB_INVALID_ADDRESS;
3427
3428 unsigned prot = 0;
3429 if (permissions & lldb::ePermissionsReadable)
3430 prot |= eMmapProtRead;
3431 if (permissions & lldb::ePermissionsWritable)
3432 prot |= eMmapProtWrite;
3433 if (permissions & lldb::ePermissionsExecutable)
3434 prot |= eMmapProtExec;
3435
3436 // TODO implement this directly in NativeProcessLinux
3437 // (and lift to NativeProcessPOSIX if/when that class is
3438 // refactored out).
3439 if (InferiorCallMmap(this, addr, 0, size, prot,
3440 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3441 m_addr_to_mmap_size[addr] = size;
3442 return Error ();
3443 } else {
3444 addr = LLDB_INVALID_ADDRESS;
3445 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3446 }
3447#endif
3448}
3449
3450Error
3451NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3452{
3453 // FIXME see comments in AllocateMemory - required lower-level
3454 // bits not in place yet (ThreadPlans)
3455 return Error ("not implemented");
3456}
3457
3458lldb::addr_t
3459NativeProcessLinux::GetSharedLibraryInfoAddress ()
3460{
3461#if 1
3462 // punt on this for now
3463 return LLDB_INVALID_ADDRESS;
3464#else
3465 // Return the image info address for the exe module
3466#if 1
3467 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3468
3469 ModuleSP module_sp;
3470 Error error = GetExeModuleSP (module_sp);
3471 if (error.Fail ())
3472 {
3473 if (log)
3474 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3475 return LLDB_INVALID_ADDRESS;
3476 }
3477
3478 if (module_sp == nullptr)
3479 {
3480 if (log)
3481 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3482 return LLDB_INVALID_ADDRESS;
3483 }
3484
3485 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3486 if (object_file_sp == nullptr)
3487 {
3488 if (log)
3489 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3490 return LLDB_INVALID_ADDRESS;
3491 }
3492
3493 return obj_file_sp->GetImageInfoAddress();
3494#else
3495 Target *target = &GetTarget();
3496 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3497 Address addr = obj_file->GetImageInfoAddress(target);
3498
3499 if (addr.IsValid())
3500 return addr.GetLoadAddress(target);
3501 return LLDB_INVALID_ADDRESS;
3502#endif
3503#endif // punt on this for now
3504}
3505
3506size_t
3507NativeProcessLinux::UpdateThreads ()
3508{
3509 // The NativeProcessLinux monitoring threads are always up to date
3510 // with respect to thread state and they keep the thread list
3511 // populated properly. All this method needs to do is return the
3512 // thread count.
3513 Mutex::Locker locker (m_threads_mutex);
3514 return m_threads.size ();
3515}
3516
3517bool
3518NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3519{
3520 arch = m_arch;
3521 return true;
3522}
3523
3524Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003525NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003526{
3527 // FIXME put this behind a breakpoint protocol class that can be
3528 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003529 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003530 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003531 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003532
3533 switch (m_arch.GetMachine ())
3534 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003535 case llvm::Triple::aarch64:
3536 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3537 return Error ();
3538
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003539 case llvm::Triple::arm:
3540 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3541 return Error ();
3542
Todd Fialaaf245d12014-06-30 21:05:18 +00003543 case llvm::Triple::x86:
3544 case llvm::Triple::x86_64:
3545 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3546 return Error ();
3547
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003548 case llvm::Triple::mips64:
3549 case llvm::Triple::mips64el:
3550 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3551 return Error ();
3552
Todd Fialaaf245d12014-06-30 21:05:18 +00003553 default:
3554 assert(false && "CPU type not supported!");
3555 return Error ("CPU type not supported");
3556 }
3557}
3558
3559Error
3560NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3561{
3562 if (hardware)
3563 return Error ("NativeProcessLinux does not support hardware breakpoints");
3564 else
3565 return SetSoftwareBreakpoint (addr, size);
3566}
3567
3568Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003569NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3570 size_t &actual_opcode_size,
3571 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003572{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003573 // FIXME put this behind a breakpoint protocol class that can be set per
3574 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003575 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003576 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3577 // linux kernel does otherwise.
3578 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003579 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003580 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003581 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003582 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003583
3584 switch (m_arch.GetMachine ())
3585 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003586 case llvm::Triple::aarch64:
3587 trap_opcode_bytes = g_aarch64_opcode;
3588 actual_opcode_size = sizeof(g_aarch64_opcode);
3589 return Error ();
3590
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003591 case llvm::Triple::arm:
3592 switch (trap_opcode_size_hint)
3593 {
3594 case 2:
3595 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3596 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3597 return Error ();
3598 case 4:
3599 trap_opcode_bytes = g_arm_breakpoint_opcode;
3600 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3601 return Error ();
3602 default:
3603 assert(false && "Unrecognised trap opcode size hint!");
3604 return Error ("Unrecognised trap opcode size hint!");
3605 }
3606
Todd Fialaaf245d12014-06-30 21:05:18 +00003607 case llvm::Triple::x86:
3608 case llvm::Triple::x86_64:
3609 trap_opcode_bytes = g_i386_opcode;
3610 actual_opcode_size = sizeof(g_i386_opcode);
3611 return Error ();
3612
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003613 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003614 trap_opcode_bytes = g_mips64_opcode;
3615 actual_opcode_size = sizeof(g_mips64_opcode);
3616 return Error ();
3617
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003618 case llvm::Triple::mips64el:
3619 trap_opcode_bytes = g_mips64el_opcode;
3620 actual_opcode_size = sizeof(g_mips64el_opcode);
3621 return Error ();
3622
Todd Fialaaf245d12014-06-30 21:05:18 +00003623 default:
3624 assert(false && "CPU type not supported!");
3625 return Error ("CPU type not supported");
3626 }
3627}
3628
3629#if 0
3630ProcessMessage::CrashReason
3631NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3632{
3633 ProcessMessage::CrashReason reason;
3634 assert(info->si_signo == SIGSEGV);
3635
3636 reason = ProcessMessage::eInvalidCrashReason;
3637
3638 switch (info->si_code)
3639 {
3640 default:
3641 assert(false && "unexpected si_code for SIGSEGV");
3642 break;
3643 case SI_KERNEL:
3644 // Linux will occasionally send spurious SI_KERNEL codes.
3645 // (this is poorly documented in sigaction)
3646 // One way to get this is via unaligned SIMD loads.
3647 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3648 break;
3649 case SEGV_MAPERR:
3650 reason = ProcessMessage::eInvalidAddress;
3651 break;
3652 case SEGV_ACCERR:
3653 reason = ProcessMessage::ePrivilegedAddress;
3654 break;
3655 }
3656
3657 return reason;
3658}
3659#endif
3660
3661
3662#if 0
3663ProcessMessage::CrashReason
3664NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3665{
3666 ProcessMessage::CrashReason reason;
3667 assert(info->si_signo == SIGILL);
3668
3669 reason = ProcessMessage::eInvalidCrashReason;
3670
3671 switch (info->si_code)
3672 {
3673 default:
3674 assert(false && "unexpected si_code for SIGILL");
3675 break;
3676 case ILL_ILLOPC:
3677 reason = ProcessMessage::eIllegalOpcode;
3678 break;
3679 case ILL_ILLOPN:
3680 reason = ProcessMessage::eIllegalOperand;
3681 break;
3682 case ILL_ILLADR:
3683 reason = ProcessMessage::eIllegalAddressingMode;
3684 break;
3685 case ILL_ILLTRP:
3686 reason = ProcessMessage::eIllegalTrap;
3687 break;
3688 case ILL_PRVOPC:
3689 reason = ProcessMessage::ePrivilegedOpcode;
3690 break;
3691 case ILL_PRVREG:
3692 reason = ProcessMessage::ePrivilegedRegister;
3693 break;
3694 case ILL_COPROC:
3695 reason = ProcessMessage::eCoprocessorError;
3696 break;
3697 case ILL_BADSTK:
3698 reason = ProcessMessage::eInternalStackError;
3699 break;
3700 }
3701
3702 return reason;
3703}
3704#endif
3705
3706#if 0
3707ProcessMessage::CrashReason
3708NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3709{
3710 ProcessMessage::CrashReason reason;
3711 assert(info->si_signo == SIGFPE);
3712
3713 reason = ProcessMessage::eInvalidCrashReason;
3714
3715 switch (info->si_code)
3716 {
3717 default:
3718 assert(false && "unexpected si_code for SIGFPE");
3719 break;
3720 case FPE_INTDIV:
3721 reason = ProcessMessage::eIntegerDivideByZero;
3722 break;
3723 case FPE_INTOVF:
3724 reason = ProcessMessage::eIntegerOverflow;
3725 break;
3726 case FPE_FLTDIV:
3727 reason = ProcessMessage::eFloatDivideByZero;
3728 break;
3729 case FPE_FLTOVF:
3730 reason = ProcessMessage::eFloatOverflow;
3731 break;
3732 case FPE_FLTUND:
3733 reason = ProcessMessage::eFloatUnderflow;
3734 break;
3735 case FPE_FLTRES:
3736 reason = ProcessMessage::eFloatInexactResult;
3737 break;
3738 case FPE_FLTINV:
3739 reason = ProcessMessage::eFloatInvalidOperation;
3740 break;
3741 case FPE_FLTSUB:
3742 reason = ProcessMessage::eFloatSubscriptRange;
3743 break;
3744 }
3745
3746 return reason;
3747}
3748#endif
3749
3750#if 0
3751ProcessMessage::CrashReason
3752NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3753{
3754 ProcessMessage::CrashReason reason;
3755 assert(info->si_signo == SIGBUS);
3756
3757 reason = ProcessMessage::eInvalidCrashReason;
3758
3759 switch (info->si_code)
3760 {
3761 default:
3762 assert(false && "unexpected si_code for SIGBUS");
3763 break;
3764 case BUS_ADRALN:
3765 reason = ProcessMessage::eIllegalAlignment;
3766 break;
3767 case BUS_ADRERR:
3768 reason = ProcessMessage::eIllegalAddress;
3769 break;
3770 case BUS_OBJERR:
3771 reason = ProcessMessage::eHardwareError;
3772 break;
3773 }
3774
3775 return reason;
3776}
3777#endif
3778
Todd Fialaaf245d12014-06-30 21:05:18 +00003779Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003780NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3781{
3782 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3783 // for it.
3784 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3785 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3786}
3787
3788Error
3789NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3790{
3791 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3792 // for it.
3793 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3794 return NativeProcessProtocol::RemoveWatchpoint(addr);
3795}
3796
3797Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003798NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003799{
3800 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003801 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003802 return op.GetError ();
3803}
3804
3805Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003806NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3807{
3808 Error error = ReadMemory(addr, buf, size, bytes_read);
3809 if (error.Fail()) return error;
3810 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3811}
3812
3813Error
3814NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003815{
3816 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003817 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003818 return op.GetError ();
3819}
3820
Chaoren Lin97ccc292015-02-03 01:51:12 +00003821Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003822NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003823 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003824{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003825 ReadRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003826 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003827 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003828}
3829
Chaoren Lin97ccc292015-02-03 01:51:12 +00003830Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003831NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3832 const char* reg_name, const RegisterValue &value)
3833{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003834 WriteRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003835 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003836 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003837}
3838
Chaoren Lin97ccc292015-02-03 01:51:12 +00003839Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003840NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3841{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003842 ReadGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003843 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003844 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003845}
3846
Chaoren Lin97ccc292015-02-03 01:51:12 +00003847Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003848NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3849{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003850 ReadFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003851 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003852 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003853}
3854
Chaoren Lin97ccc292015-02-03 01:51:12 +00003855Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003856NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3857{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003858 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003859 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003860 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003861}
3862
Chaoren Lin97ccc292015-02-03 01:51:12 +00003863Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003864NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3865{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003866 WriteGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003867 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003868 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003869}
3870
Chaoren Lin97ccc292015-02-03 01:51:12 +00003871Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003872NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3873{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003874 WriteFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003875 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003876 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003877}
3878
Chaoren Lin97ccc292015-02-03 01:51:12 +00003879Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003880NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3881{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003882 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003883 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003884 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003885}
3886
Chaoren Lin97ccc292015-02-03 01:51:12 +00003887Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003888NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3889{
Todd Fialaaf245d12014-06-30 21:05:18 +00003890 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3891
3892 if (log)
3893 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3894 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003895 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003896 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003897 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003898 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3899 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003900}
3901
Chaoren Lin97ccc292015-02-03 01:51:12 +00003902Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003903NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3904{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003905 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003906 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003907 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003908}
3909
Chaoren Lin97ccc292015-02-03 01:51:12 +00003910Error
3911NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003912{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003913 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003914 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003915 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003916}
3917
Chaoren Lin97ccc292015-02-03 01:51:12 +00003918Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003919NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3920{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003921 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003922 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003923 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003924}
3925
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003926Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003927NativeProcessLinux::Detach(lldb::tid_t tid)
3928{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003929 if (tid == LLDB_INVALID_THREAD_ID)
3930 return Error();
3931
3932 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003933 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003934 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003935}
3936
3937bool
3938NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3939{
3940 int target_fd = open(path, flags, 0666);
3941
3942 if (target_fd == -1)
3943 return false;
3944
Pavel Labath493c3a12015-02-04 10:36:57 +00003945 if (dup2(target_fd, fd) == -1)
3946 return false;
3947
3948 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003949}
3950
3951void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003952NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003953{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003954 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003955 error = m_monitor_up->Initialize();
3956 if (error.Fail()) {
3957 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003958 }
3959}
3960
Todd Fialaaf245d12014-06-30 21:05:18 +00003961bool
3962NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3963{
3964 for (auto thread_sp : m_threads)
3965 {
3966 assert (thread_sp && "thread list should not contain NULL threads");
3967 if (thread_sp->GetID () == thread_id)
3968 {
3969 // We have this thread.
3970 return true;
3971 }
3972 }
3973
3974 // We don't have this thread.
3975 return false;
3976}
3977
3978NativeThreadProtocolSP
3979NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3980{
3981 // CONSIDER organize threads by map - we can do better than linear.
3982 for (auto thread_sp : m_threads)
3983 {
3984 if (thread_sp->GetID () == thread_id)
3985 return thread_sp;
3986 }
3987
3988 // We don't have this thread.
3989 return NativeThreadProtocolSP ();
3990}
3991
3992bool
3993NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3994{
3995 Mutex::Locker locker (m_threads_mutex);
3996 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3997 {
3998 if (*it && ((*it)->GetID () == thread_id))
3999 {
4000 m_threads.erase (it);
4001 return true;
4002 }
4003 }
4004
4005 // Didn't find it.
4006 return false;
4007}
4008
4009NativeThreadProtocolSP
4010NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4011{
4012 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4013
4014 Mutex::Locker locker (m_threads_mutex);
4015
4016 if (log)
4017 {
4018 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4019 __FUNCTION__,
4020 GetID (),
4021 thread_id);
4022 }
4023
4024 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4025
4026 // If this is the first thread, save it as the current thread
4027 if (m_threads.empty ())
4028 SetCurrentThreadID (thread_id);
4029
4030 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4031 m_threads.push_back (thread_sp);
4032
4033 return thread_sp;
4034}
4035
Todd Fialaaf245d12014-06-30 21:05:18 +00004036Error
4037NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4038{
Todd Fiala75f47c32014-10-11 21:42:09 +00004039 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00004040
4041 Error error;
4042
4043 // Get a linux thread pointer.
4044 if (!thread_sp)
4045 {
4046 error.SetErrorString ("null thread_sp");
4047 if (log)
4048 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4049 return error;
4050 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004051 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00004052
4053 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004054 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00004055 if (!context_sp)
4056 {
4057 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4058 if (log)
4059 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4060 return error;
4061 }
4062
4063 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00004064 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00004065 if (error.Fail ())
4066 {
4067 if (log)
4068 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4069 return error;
4070 }
4071 else
4072 {
4073 if (log)
4074 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4075 }
4076
4077 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4078 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4079 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004080 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00004081 {
4082 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004083 if (breakpoint_addr >= breakpoint_size)
4084 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00004085 }
4086
4087 // Check if we stopped because of a breakpoint.
4088 NativeBreakpointSP breakpoint_sp;
4089 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4090 if (!error.Success () || !breakpoint_sp)
4091 {
4092 // We didn't find one at a software probe location. Nothing to do.
4093 if (log)
4094 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4095 return Error ();
4096 }
4097
4098 // If the breakpoint is not a software breakpoint, nothing to do.
4099 if (!breakpoint_sp->IsSoftwareBreakpoint ())
4100 {
4101 if (log)
4102 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4103 return Error ();
4104 }
4105
4106 //
4107 // We have a software breakpoint and need to adjust the PC.
4108 //
4109
4110 // Sanity check.
4111 if (breakpoint_size == 0)
4112 {
4113 // Nothing to do! How did we get here?
4114 if (log)
4115 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);
4116 return Error ();
4117 }
4118
4119 // Change the program counter.
4120 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004121 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 +00004122
4123 error = context_sp->SetPC (breakpoint_addr);
4124 if (error.Fail ())
4125 {
4126 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004127 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 +00004128 return error;
4129 }
4130
4131 return error;
4132}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004133
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004134Error
4135NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4136{
4137 char maps_file_name[32];
4138 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4139
4140 FileSpec maps_file_spec(maps_file_name, false);
4141 if (!maps_file_spec.Exists()) {
4142 file_spec.Clear();
4143 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4144 }
4145
4146 FileSpec module_file_spec(module_path, true);
4147
4148 std::ifstream maps_file(maps_file_name);
4149 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4150 StringRef maps_data(maps_data_str.c_str());
4151
4152 while (!maps_data.empty())
4153 {
4154 StringRef maps_row;
4155 std::tie(maps_row, maps_data) = maps_data.split('\n');
4156
4157 SmallVector<StringRef, 16> maps_columns;
4158 maps_row.split(maps_columns, StringRef(" "), -1, false);
4159
4160 if (maps_columns.size() >= 6)
4161 {
4162 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4163 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4164 return Error();
4165 }
4166 }
4167
4168 file_spec.Clear();
4169 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4170 module_file_spec.GetFilename().AsCString(), GetID());
4171}
Pavel Labathc0765592015-05-06 10:46:34 +00004172
Pavel Labath5eb721e2015-05-07 08:30:31 +00004173Error
Pavel Labathc0765592015-05-06 10:46:34 +00004174NativeProcessLinux::DoResume(
4175 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004176 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00004177 bool error_when_already_running)
4178{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004179 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4180
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004181 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4182 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004183
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004184 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00004185 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004186 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00004187
4188 lldbassert(!(error_when_already_running && !is_stopped));
4189
Pavel Labathc0765592015-05-06 10:46:34 +00004190 if (!is_stopped)
4191 {
4192 // It's not an error, just a log, if the error_when_already_running flag is not set.
4193 // This covers cases where, for instance, we're just trying to resume all threads
4194 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004195 if (log)
4196 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4197 __FUNCTION__,
4198 tid);
4199 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00004200 }
4201
4202 // Before we do the resume below, first check if we have a pending
4203 // stop notification this is currently or was previously waiting for
4204 // this thread to stop. This is potentially a buggy situation since
4205 // we're ostensibly waiting for threads to stop before we send out the
4206 // pending notification, and here we are resuming one before we send
4207 // out the pending stop notification.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004208 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004209 {
4210 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4211 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004212 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 +00004213 }
4214 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0)
4215 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004216 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 +00004217 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4218 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004219 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00004220 __FUNCTION__,
4221 m_pending_notification_up->triggering_tid,
4222 tid);
4223 }
4224 }
4225 }
4226
4227 // Request a resume. We expect this to be synchronous and the system
4228 // to reflect it is running after this completes.
4229 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004230 if (error.Success())
4231 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00004232 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004233 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004234 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00004235 __FUNCTION__, tid, error.AsCString ());
4236 }
4237
Pavel Labath5eb721e2015-05-07 08:30:31 +00004238 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004239}
4240
4241//===----------------------------------------------------------------------===//
4242
4243void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004244NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004245 const ThreadIDSet &wait_for_stop_tids)
Pavel Labathc0765592015-05-06 10:46:34 +00004246{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004247 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004248 std::lock_guard<std::mutex> lock(m_event_mutex);
4249
Pavel Labath5eb721e2015-05-07 08:30:31 +00004250 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004251 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004252 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)",
Pavel Labathc0765592015-05-06 10:46:34 +00004253 __FUNCTION__, triggering_tid, wait_for_stop_tids.size());
4254 }
4255
Pavel Labathed89c7f2015-05-06 12:22:37 +00004256 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labath337f3eb2015-05-08 08:57:45 +00004257 triggering_tid, wait_for_stop_tids, ThreadIDSet())));
Pavel Labathc0765592015-05-06 10:46:34 +00004258
Pavel Labath5eb721e2015-05-07 08:30:31 +00004259 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004260 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004261 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004262 }
4263}
4264
4265void
Pavel Labath337f3eb2015-05-08 08:57:45 +00004266NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004267{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004268 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004269 std::lock_guard<std::mutex> lock(m_event_mutex);
4270
Pavel Labath5eb721e2015-05-07 08:30:31 +00004271 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004272 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004273 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004274 __FUNCTION__, triggering_tid);
4275 }
4276
Pavel Labath337f3eb2015-05-08 08:57:45 +00004277 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00004278
Pavel Labath5eb721e2015-05-07 08:30:31 +00004279 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004280 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004281 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004282 }
4283}
4284
4285void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004286NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004287 lldb::tid_t skip_stop_request_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004288{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004289 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004290 std::lock_guard<std::mutex> lock(m_event_mutex);
4291
Pavel Labath5eb721e2015-05-07 08:30:31 +00004292 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004293 {
Pavel Labath337f3eb2015-05-08 08:57:45 +00004294 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tid: %" PRIu64 ")",
4295 __FUNCTION__, triggering_tid, skip_stop_request_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004296 }
4297
Pavel Labathed89c7f2015-05-06 12:22:37 +00004298 DoStopThreads(PendingNotificationUP(new PendingNotification(
Pavel Labathc0765592015-05-06 10:46:34 +00004299 triggering_tid,
Pavel Labath337f3eb2015-05-08 08:57:45 +00004300 ThreadIDSet(),
4301 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : 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
4310NativeProcessLinux::SignalIfRequirementsSatisfied()
4311{
4312 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4313 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00004314 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4315 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004316 m_pending_notification_up.reset();
4317 }
4318}
4319
4320bool
4321NativeProcessLinux::RequestStopOnAllSpecifiedThreads()
4322{
4323 // Request a stop for all the thread stops that need to be stopped
4324 // and are not already known to be stopped. Keep a list of all the
4325 // threads from which we still need to hear a stop reply.
4326
4327 ThreadIDSet sent_tids;
4328 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4329 {
4330 // Validate we know about all tids for which we must first receive a stop before
4331 // triggering the deferred stop notification.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004332 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4333 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004334
4335 // If the pending stop thread is currently running, we need to send it a stop request.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004336 if (StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00004337 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004338 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00004339 sent_tids.insert (tid);
4340 }
4341 }
4342 // We only need to wait for the sent_tids - so swap our wait set
4343 // to the sent tids. The rest are already stopped and we won't
4344 // be receiving stop notifications for them.
4345 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4346
4347 // Succeeded, keep running.
4348 return true;
4349}
4350
4351void
4352NativeProcessLinux::RequestStopOnAllRunningThreads()
4353{
4354 // Request a stop for all the thread stops that need to be stopped
4355 // and are not already known to be stopped. Keep a list of all the
4356 // threads from which we still need to hear a stop reply.
4357
4358 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004359 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00004360 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004361 // We only care about running threads
4362 if (StateIsStoppedState(thread_sp->GetState(), true))
4363 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00004364
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004365 const lldb::tid_t tid = thread_sp->GetID();
Pavel Labathc0765592015-05-06 10:46:34 +00004366
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004367 // Request this thread stop if the tid stop request is not explicitly ignored.
4368 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0;
4369 if (!skip_stop_request)
4370 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4371
4372 // Even if we skipped sending the stop request for other reasons (like stepping),
4373 // we still need to wait for that stepping thread to notify completion/stop.
4374 sent_tids.insert (tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004375 }
4376
4377 // Set the wait list to the set of tids for which we requested stops.
4378 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4379}
4380
Pavel Labathc0765592015-05-06 10:46:34 +00004381
Pavel Labath5eb721e2015-05-07 08:30:31 +00004382Error
4383NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004384{
4385 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004386 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4387 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004388
4389 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004390 auto& context = thread_sp->GetThreadContext();
4391 const auto stop_was_requested = context.stop_requested;
4392 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00004393
4394 // If we have a pending notification, remove this from the set.
4395 if (m_pending_notification_up)
4396 {
4397 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4398 SignalIfRequirementsSatisfied();
4399 }
4400
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004401 Error error;
4402 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00004403 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004404 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004405 // We can end up here if stop was initiated by LLGS but by this time a
4406 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004407 if (log)
4408 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004409 error = context.request_resume_function (tid, true);
4410 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004411 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004412 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
4413 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00004414 }
4415 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004416 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004417}
4418
4419void
Pavel Labathed89c7f2015-05-06 12:22:37 +00004420NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00004421{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004422 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4423 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00004424 {
4425 // Yikes - we've already got a pending signal notification in progress.
4426 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00004427 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 +00004428 __FUNCTION__,
4429 m_pending_notification_up->triggering_tid,
4430 notification_up->triggering_tid);
4431 }
4432 m_pending_notification_up = std::move(notification_up);
4433
4434 if (m_pending_notification_up->request_stop_on_all_unstopped_threads)
4435 RequestStopOnAllRunningThreads();
4436 else
4437 {
4438 if (!RequestStopOnAllSpecifiedThreads())
4439 return;
4440 }
4441
Pavel Labathed89c7f2015-05-06 12:22:37 +00004442 SignalIfRequirementsSatisfied();
Pavel Labathc0765592015-05-06 10:46:34 +00004443}
4444
4445void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004446NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004447{
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004448 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
4449 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00004450
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004451 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00004452 {
4453 // We will need to wait for this new thread to stop as well before firing the
4454 // notification.
4455 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004456 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00004457 }
4458}
4459
4460void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004461NativeProcessLinux::ThreadDidDie (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004462{
Pavel Labathc0765592015-05-06 10:46:34 +00004463 // If we have a pending notification, remove this from the set.
4464 if (m_pending_notification_up)
4465 {
4466 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4467 SignalIfRequirementsSatisfied();
4468 }
4469}
4470
Pavel Labath5eb721e2015-05-07 08:30:31 +00004471Error
4472NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00004473{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004474 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004475 std::lock_guard<std::mutex> lock(m_event_mutex);
4476
Pavel Labath5eb721e2015-05-07 08:30:31 +00004477 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004478 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004479 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)",
Pavel Labathc0765592015-05-06 10:46:34 +00004480 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
4481 }
4482
Pavel Labath5eb721e2015-05-07 08:30:31 +00004483 Error error = ThreadDidStop (tid, initiated_by_llgs);
Pavel Labathc0765592015-05-06 10:46:34 +00004484
Pavel Labath5eb721e2015-05-07 08:30:31 +00004485 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004486 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004487 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004488 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004489
4490 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004491}
4492
Pavel Labath5eb721e2015-05-07 08:30:31 +00004493Error
Pavel Labathc0765592015-05-06 10:46:34 +00004494NativeProcessLinux::RequestThreadResume (lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004495 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004496{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004497 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004498 std::lock_guard<std::mutex> lock(m_event_mutex);
4499
Pavel Labath5eb721e2015-05-07 08:30:31 +00004500 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004501 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004502 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004503 __FUNCTION__, tid);
4504 }
4505
Pavel Labath5eb721e2015-05-07 08:30:31 +00004506 Error error = DoResume(tid, request_thread_resume_function, true);
Pavel Labathc0765592015-05-06 10:46:34 +00004507
Pavel Labath5eb721e2015-05-07 08:30:31 +00004508 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004509 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004510 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004511 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004512
4513 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004514}
4515
Pavel Labath5eb721e2015-05-07 08:30:31 +00004516Error
Pavel Labathc0765592015-05-06 10:46:34 +00004517NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004518 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
Pavel Labathc0765592015-05-06 10:46:34 +00004519{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004520 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004521 std::lock_guard<std::mutex> lock(m_event_mutex);
4522
Pavel Labath5eb721e2015-05-07 08:30:31 +00004523 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004524 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004525 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00004526 __FUNCTION__, tid);
4527 }
4528
Pavel Labath5eb721e2015-05-07 08:30:31 +00004529 Error error = DoResume (tid, request_thread_resume_function, false);
Pavel Labathc0765592015-05-06 10:46:34 +00004530
Pavel Labath5eb721e2015-05-07 08:30:31 +00004531 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004532 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004533 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004534 }
Pavel Labath5eb721e2015-05-07 08:30:31 +00004535
4536 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00004537}
4538
4539void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004540NativeProcessLinux::NotifyThreadCreate(lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004541{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004542 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004543 std::lock_guard<std::mutex> lock(m_event_mutex);
4544
Pavel Labath5eb721e2015-05-07 08:30:31 +00004545 if (log)
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004546 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004547
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00004548 ThreadWasCreated(tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004549
Pavel Labath5eb721e2015-05-07 08:30:31 +00004550 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004551 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004552 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004553 }
4554}
4555
4556void
Pavel Labath5eb721e2015-05-07 08:30:31 +00004557NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00004558{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004559 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004560 std::lock_guard<std::mutex> lock(m_event_mutex);
4561
Pavel Labath5eb721e2015-05-07 08:30:31 +00004562 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004563 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004564 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004565 }
4566
Pavel Labath5eb721e2015-05-07 08:30:31 +00004567 ThreadDidDie(tid);
Pavel Labathc0765592015-05-06 10:46:34 +00004568
Pavel Labath5eb721e2015-05-07 08:30:31 +00004569 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004570 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004571 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004572 }
4573}
4574
4575void
4576NativeProcessLinux::ResetForExec ()
4577{
Pavel Labath5eb721e2015-05-07 08:30:31 +00004578 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00004579 std::lock_guard<std::mutex> lock(m_event_mutex);
4580
Pavel Labath5eb721e2015-05-07 08:30:31 +00004581 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004582 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004583 log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004584 }
4585
4586 // Clear the pending notification if there was one.
4587 m_pending_notification_up.reset ();
4588
Pavel Labath5eb721e2015-05-07 08:30:31 +00004589 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00004590 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00004591 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00004592 }
4593}