blob: be07b43658032eda56d6becdc0c7b113f4bae307 [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
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Pavel Labath5b981ab2015-05-29 12:53:54 +000014#include <semaphore.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000015#include <string.h>
16#include <stdint.h>
17#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000018
19// C++ Includes
20#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000021#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000022#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000023#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000024#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000025
26// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000027#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Core/Error.h"
29#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000030#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000032#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000033#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000034#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000035#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000036#include "lldb/Host/ThreadLauncher.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000037#include "lldb/Target/Platform.h"
Zachary Turner90aff472015-03-03 23:36:51 +000038#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000040#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000041#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Utility/PseudoTerminal.h"
43
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000044#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000046#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "NativeThreadLinux.h"
48#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000049#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000050
Tamas Berghammerd8584872015-02-06 10:57:40 +000051// System includes - They have to be included after framework includes because they define some
52// macros which collide with variable names in other modules
53#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000055
Pavel Labathdf7c6992015-06-17 18:38:49 +000056#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000058#include <sys/user.h>
59#include <sys/wait.h>
60
Vince Harron8b335672015-05-12 01:10:56 +000061#include "lldb/Host/linux/Personality.h"
62#include "lldb/Host/linux/Ptrace.h"
63#include "lldb/Host/linux/Signalfd.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000064#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000065#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000066
Todd Fiala0bce1b62014-08-17 00:10:50 +000067#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000068
69// Support hardware breakpoints in case it has not been defined
70#ifndef TRAP_HWBKPT
71 #define TRAP_HWBKPT 4
72#endif
73
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000074using namespace lldb;
75using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000076using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000077using namespace llvm;
78
Todd Fialaaf245d12014-06-30 21:05:18 +000079// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000080
81static bool ProcessVmReadvSupported()
82{
83 static bool is_supported;
84 static std::once_flag flag;
85
86 std::call_once(flag, [] {
87 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
88
89 uint32_t source = 0x47424742;
90 uint32_t dest = 0;
91
92 struct iovec local, remote;
93 remote.iov_base = &source;
94 local.iov_base = &dest;
95 remote.iov_len = local.iov_len = sizeof source;
96
97 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
98 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
99 is_supported = (res == sizeof(source) && source == dest);
100 if (log)
101 {
102 if (is_supported)
103 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
104 __FUNCTION__);
105 else
106 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
107 __FUNCTION__, strerror(errno));
108 }
109 });
110
111 return is_supported;
112}
113
Todd Fialaaf245d12014-06-30 21:05:18 +0000114namespace
115{
Todd Fialaaf245d12014-06-30 21:05:18 +0000116 const UnixSignals&
117 GetUnixSignals ()
118 {
119 static process_linux::LinuxSignals signals;
120 return signals;
121 }
122
Todd Fialaaf245d12014-06-30 21:05:18 +0000123 Error
124 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
125 {
126 // Grab process info for the running process.
127 ProcessInstanceInfo process_info;
128 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000129 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000130
131 // Resolve the executable module.
132 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000133 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000134 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
135 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000136 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000137 exe_module_sp,
138 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
139
140 if (!error.Success ())
141 return error;
142
143 // Check if we've got our architecture from the exe_module.
144 arch = exe_module_sp->GetArchitecture ();
145 if (arch.IsValid ())
146 return Error();
147 else
148 return Error("failed to retrieve a valid architecture from the exe module");
149 }
150
151 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000152 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000153 {
154 uint8_t *ptr = (uint8_t *)bytes;
155 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
156 for(uint32_t i=0; i<loop_count; i++)
157 {
158 s.Printf ("[%x]", *ptr);
159 ptr++;
160 }
161 }
162
163 void
164 PtraceDisplayBytes(int &req, void *data, size_t data_size)
165 {
166 StreamString buf;
167 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
168 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
169
170 if (verbose_log)
171 {
172 switch(req)
173 {
174 case PTRACE_POKETEXT:
175 {
176 DisplayBytes(buf, &data, 8);
177 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
178 break;
179 }
180 case PTRACE_POKEDATA:
181 {
182 DisplayBytes(buf, &data, 8);
183 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
184 break;
185 }
186 case PTRACE_POKEUSER:
187 {
188 DisplayBytes(buf, &data, 8);
189 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
190 break;
191 }
192 case PTRACE_SETREGS:
193 {
194 DisplayBytes(buf, data, data_size);
195 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
196 break;
197 }
198 case PTRACE_SETFPREGS:
199 {
200 DisplayBytes(buf, data, data_size);
201 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
202 break;
203 }
204 case PTRACE_SETSIGINFO:
205 {
206 DisplayBytes(buf, data, sizeof(siginfo_t));
207 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
208 break;
209 }
210 case PTRACE_SETREGSET:
211 {
212 // Extract iov_base from data, which is a pointer to the struct IOVEC
213 DisplayBytes(buf, *(void **)data, data_size);
214 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
215 break;
216 }
217 default:
218 {
219 }
220 }
221 }
222 }
223
Todd Fialaaf245d12014-06-30 21:05:18 +0000224 //------------------------------------------------------------------------------
225 // Static implementations of NativeProcessLinux::ReadMemory and
226 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
227 // functions without needed to go thru the thread funnel.
228
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000229 size_t
230 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000231 lldb::pid_t pid,
232 lldb::addr_t vm_addr,
233 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000234 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000235 Error &error)
236 {
237 // ptrace word size is determined by the host, not the child
238 static const unsigned word_size = sizeof(void*);
239 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000240 size_t bytes_read;
241 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000242 long data;
243
244 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
245 if (log)
246 ProcessPOSIXLog::IncNestLevel();
247 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
248 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
249 pid, word_size, (void*)vm_addr, buf, size);
250
251 assert(sizeof(data) >= word_size);
252 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
253 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000254 data = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000255 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000256 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000257 if (log)
258 ProcessPOSIXLog::DecNestLevel();
259 return bytes_read;
260 }
261
262 remainder = size - bytes_read;
263 remainder = remainder > word_size ? word_size : remainder;
264
265 // Copy the data into our buffer
266 for (unsigned i = 0; i < remainder; ++i)
267 dst[i] = ((data >> i*8) & 0xFF);
268
269 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
270 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
271 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
272 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
273 {
274 uintptr_t print_dst = 0;
275 // Format bytes from data by moving into print_dst for log output
276 for (unsigned i = 0; i < remainder; ++i)
277 print_dst |= (((data >> i*8) & 0xFF) << i*8);
278 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
279 (void*)vm_addr, print_dst, (unsigned long)data);
280 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000281 vm_addr += word_size;
282 dst += word_size;
283 }
284
285 if (log)
286 ProcessPOSIXLog::DecNestLevel();
287 return bytes_read;
288 }
289
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000290 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000291 DoWriteMemory(
292 lldb::pid_t pid,
293 lldb::addr_t vm_addr,
294 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000295 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000296 Error &error)
297 {
298 // ptrace word size is determined by the host, not the child
299 static const unsigned word_size = sizeof(void*);
300 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000301 size_t bytes_written = 0;
302 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000303
304 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
305 if (log)
306 ProcessPOSIXLog::IncNestLevel();
307 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
308 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
309 pid, word_size, (void*)vm_addr, buf, size);
310
311 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
312 {
313 remainder = size - bytes_written;
314 remainder = remainder > word_size ? word_size : remainder;
315
316 if (remainder == word_size)
317 {
318 unsigned long data = 0;
319 assert(sizeof(data) >= word_size);
320 for (unsigned i = 0; i < word_size; ++i)
321 data |= (unsigned long)src[i] << i*8;
322
323 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
324 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
325 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
326 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
327 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000328 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000329
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000330 if (NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000332 if (log)
333 ProcessPOSIXLog::DecNestLevel();
334 return bytes_written;
335 }
336 }
337 else
338 {
339 unsigned char buff[8];
340 if (DoReadMemory(pid, vm_addr,
341 buff, word_size, error) != word_size)
342 {
343 if (log)
344 ProcessPOSIXLog::DecNestLevel();
345 return bytes_written;
346 }
347
348 memcpy(buff, src, remainder);
349
350 if (DoWriteMemory(pid, vm_addr,
351 buff, word_size, error) != word_size)
352 {
353 if (log)
354 ProcessPOSIXLog::DecNestLevel();
355 return bytes_written;
356 }
357
358 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
359 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
360 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
361 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
362 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000363 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000364 }
365
366 vm_addr += word_size;
367 src += word_size;
368 }
369 if (log)
370 ProcessPOSIXLog::DecNestLevel();
371 return bytes_written;
372 }
373
374 //------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 /// @class ReadOperation
376 /// @brief Implements NativeProcessLinux::ReadMemory.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000377 class ReadOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000378 {
379 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000380 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000381 lldb::addr_t addr,
382 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000383 size_t size,
384 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000385 Operation (),
386 m_addr (addr),
387 m_buff (buff),
388 m_size (size),
389 m_result (result)
390 {
391 }
392
393 void Execute (NativeProcessLinux *process) override;
394
395 private:
396 lldb::addr_t m_addr;
397 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000398 size_t m_size;
399 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000400 };
401
402 void
403 ReadOperation::Execute (NativeProcessLinux *process)
404 {
405 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
406 }
407
408 //------------------------------------------------------------------------------
409 /// @class WriteOperation
410 /// @brief Implements NativeProcessLinux::WriteMemory.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000411 class WriteOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000412 {
413 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000414 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000415 lldb::addr_t addr,
416 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000417 size_t size,
418 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000419 Operation (),
420 m_addr (addr),
421 m_buff (buff),
422 m_size (size),
423 m_result (result)
424 {
425 }
426
427 void Execute (NativeProcessLinux *process) override;
428
429 private:
430 lldb::addr_t m_addr;
431 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000432 size_t m_size;
433 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000434 };
435
436 void
437 WriteOperation::Execute(NativeProcessLinux *process)
438 {
439 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
440 }
441
442 //------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000443 /// @class ResumeOperation
444 /// @brief Implements NativeProcessLinux::Resume.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000445 class ResumeOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000446 {
447 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000448 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
449 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000450
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000451 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000452
453 private:
454 lldb::tid_t m_tid;
455 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000456 };
457
458 void
459 ResumeOperation::Execute(NativeProcessLinux *monitor)
460 {
461 intptr_t data = 0;
462
463 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
464 data = m_signo;
465
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000466 NativeProcessLinux::PtraceWrapper(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000467 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000468 {
469 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
470
471 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000472 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000473 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000474 }
475
476 //------------------------------------------------------------------------------
477 /// @class SingleStepOperation
478 /// @brief Implements NativeProcessLinux::SingleStep.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000479 class SingleStepOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000480 {
481 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000482 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
483 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000484
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000485 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000486
487 private:
488 lldb::tid_t m_tid;
489 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000490 };
491
492 void
493 SingleStepOperation::Execute(NativeProcessLinux *monitor)
494 {
495 intptr_t data = 0;
496
497 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
498 data = m_signo;
499
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000500 NativeProcessLinux::PtraceWrapper(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000501 }
502
503 //------------------------------------------------------------------------------
504 /// @class SiginfoOperation
505 /// @brief Implements NativeProcessLinux::GetSignalInfo.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000506 class SiginfoOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000507 {
508 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000509 SiginfoOperation(lldb::tid_t tid, void *info)
510 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000511
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000512 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000513
514 private:
515 lldb::tid_t m_tid;
516 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +0000517 };
518
519 void
520 SiginfoOperation::Execute(NativeProcessLinux *monitor)
521 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000522 NativeProcessLinux::PtraceWrapper(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000523 }
524
525 //------------------------------------------------------------------------------
526 /// @class EventMessageOperation
527 /// @brief Implements NativeProcessLinux::GetEventMessage.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000528 class EventMessageOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000529 {
530 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000531 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
532 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000533
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000534 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000535
536 private:
537 lldb::tid_t m_tid;
538 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +0000539 };
540
541 void
542 EventMessageOperation::Execute(NativeProcessLinux *monitor)
543 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000544 NativeProcessLinux::PtraceWrapper(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000545 }
546
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000547 class DetachOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000548 {
549 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000550 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000551
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000552 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000553
554 private:
555 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000556 };
557
558 void
559 DetachOperation::Execute(NativeProcessLinux *monitor)
560 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000561 NativeProcessLinux::PtraceWrapper(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000562 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000563} // end of anonymous namespace
564
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000565// Simple helper function to ensure flags are enabled on the given file
566// descriptor.
567static Error
568EnsureFDFlags(int fd, int flags)
569{
570 Error error;
571
572 int status = fcntl(fd, F_GETFL);
573 if (status == -1)
574 {
575 error.SetErrorToErrno();
576 return error;
577 }
578
579 if (fcntl(fd, F_SETFL, status | flags) == -1)
580 {
581 error.SetErrorToErrno();
582 return error;
583 }
584
585 return error;
586}
587
588// This class encapsulates the privileged thread which performs all ptrace and wait operations on
589// the inferior. The thread consists of a main loop which waits for events and processes them
590// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
591// the inferior process. Upon receiving this signal we do a waitpid to get more information
592// and dispatch to NativeProcessLinux::MonitorCallback.
593// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
594// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
595// pipe, and the completion of the operation is signalled over the semaphore.
596// - thread exit event: this is signaled from the Monitor destructor by closing the write end
597// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000598class NativeProcessLinux::Monitor
599{
Pavel Labath1107b5a2015-04-17 14:07:49 +0000600private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000601 // The initial monitor operation (launch or attach). It returns a inferior process id.
602 std::unique_ptr<InitialOperation> m_initial_operation_up;
603
604 ::pid_t m_child_pid = -1;
605 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000606
607 enum { READ, WRITE };
608 int m_pipefd[2] = {-1, -1};
609 int m_signal_fd = -1;
610 HostThread m_thread;
611
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000612 // current operation which must be executed on the priviliged thread
613 Mutex m_operation_mutex;
614 Operation *m_operation = nullptr;
615 sem_t m_operation_sem;
616 Error m_operation_error;
617
Pavel Labath45f5cb32015-05-05 15:05:50 +0000618 unsigned m_operation_nesting_level = 0;
619
620 static constexpr char operation_command = 'o';
621 static constexpr char begin_block_command = '{';
622 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000623
Pavel Labath1107b5a2015-04-17 14:07:49 +0000624 void
625 HandleSignals();
626
627 void
628 HandleWait();
629
630 // Returns true if the thread should exit.
631 bool
632 HandleCommands();
633
634 void
635 MainLoop();
636
637 static void *
638 RunMonitor(void *arg);
639
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000640 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000641 WaitForAck();
642
643 void
644 BeginOperationBlock()
645 {
646 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
647 WaitForAck();
648 }
649
650 void
651 EndOperationBlock()
652 {
653 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
654 WaitForAck();
655 }
656
Pavel Labath1107b5a2015-04-17 14:07:49 +0000657public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000658 Monitor(const InitialOperation &initial_operation,
659 NativeProcessLinux *native_process)
660 : m_initial_operation_up(new InitialOperation(initial_operation)),
661 m_native_process(native_process)
662 {
663 sem_init(&m_operation_sem, 0, 0);
664 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000665
666 ~Monitor();
667
668 Error
669 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000670
671 void
Pavel Labath45f5cb32015-05-05 15:05:50 +0000672 Terminate();
673
674 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000675 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000676
677 class ScopedOperationLock {
678 Monitor &m_monitor;
679
680 public:
681 ScopedOperationLock(Monitor &monitor)
682 : m_monitor(monitor)
683 { m_monitor.BeginOperationBlock(); }
684
685 ~ScopedOperationLock()
686 { m_monitor.EndOperationBlock(); }
687 };
Pavel Labath1107b5a2015-04-17 14:07:49 +0000688};
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000689constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +0000690constexpr char NativeProcessLinux::Monitor::begin_block_command;
691constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000692
693Error
694NativeProcessLinux::Monitor::Initialize()
695{
696 Error error;
697
698 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
699 // listening for these signals over a signalfd file descriptors. This allows us to wait for
700 // multiple kinds of events with select.
701 sigset_t signals;
702 sigemptyset(&signals);
703 sigaddset(&signals, SIGCHLD);
704 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
705 if (m_signal_fd < 0)
706 {
707 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
708 __FUNCTION__, strerror(errno));
709
710 }
711
712 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
713 {
714 error.SetErrorToErrno();
715 return error;
716 }
717
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000718 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
719 return error;
720 }
721
722 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
723 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000724 if (!m_thread.IsJoinable())
725 return Error("Failed to create monitor thread for NativeProcessLinux.");
726
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000727 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000728 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000729}
730
731void
732NativeProcessLinux::Monitor::DoOperation(Operation *op)
733{
734 if (m_thread.EqualsThread(pthread_self())) {
735 // If we're on the Monitor thread, we can simply execute the operation.
736 op->Execute(m_native_process);
737 return;
738 }
739
740 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
741 Mutex::Locker lock(m_operation_mutex);
742
743 m_operation = op;
744
745 // notify the thread that an operation is ready to be processed
746 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
747
Pavel Labath45f5cb32015-05-05 15:05:50 +0000748 WaitForAck();
749}
750
751void
752NativeProcessLinux::Monitor::Terminate()
753{
754 if (m_pipefd[WRITE] >= 0)
755 {
756 close(m_pipefd[WRITE]);
757 m_pipefd[WRITE] = -1;
758 }
759 if (m_thread.IsJoinable())
760 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +0000761}
762
Pavel Labath1107b5a2015-04-17 14:07:49 +0000763NativeProcessLinux::Monitor::~Monitor()
764{
Pavel Labath45f5cb32015-05-05 15:05:50 +0000765 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +0000766 if (m_pipefd[READ] >= 0)
767 close(m_pipefd[READ]);
768 if (m_signal_fd >= 0)
769 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000770 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000771}
772
773void
774NativeProcessLinux::Monitor::HandleSignals()
775{
776 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
777
778 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
779 // all the information from waitpid(). We just need to read all the signals so that we can
780 // sleep next time we reach select().
781 while (true)
782 {
783 signalfd_siginfo info;
784 ssize_t size = read(m_signal_fd, &info, sizeof info);
785 if (size == -1)
786 {
787 if (errno == EAGAIN || errno == EWOULDBLOCK)
788 break; // We are done.
789 if (errno == EINTR)
790 continue;
791 if (log)
792 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
793 __FUNCTION__, strerror(errno));
794 break;
795 }
796 if (size != sizeof info)
797 {
798 // We got incomplete information structure. This should not happen, let's just log
799 // that.
800 if (log)
801 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
802 "structure size is %zd, read returned %zd bytes",
803 __FUNCTION__, sizeof info, size);
804 break;
805 }
806 if (log)
807 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
808 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
809 }
810}
811
812void
813NativeProcessLinux::Monitor::HandleWait()
814{
815 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
816 // Process all pending waitpid notifications.
817 while (true)
818 {
819 int status = -1;
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000820 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000821
822 if (wait_pid == 0)
823 break; // We are done.
824
825 if (wait_pid == -1)
826 {
827 if (errno == EINTR)
828 continue;
829
830 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000831 log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
832 __FUNCTION__, strerror(errno));
Pavel Labath1107b5a2015-04-17 14:07:49 +0000833 break;
834 }
835
836 bool exited = false;
837 int signal = 0;
838 int exit_status = 0;
839 const char *status_cstr = NULL;
840 if (WIFSTOPPED(status))
841 {
842 signal = WSTOPSIG(status);
843 status_cstr = "STOPPED";
844 }
845 else if (WIFEXITED(status))
846 {
847 exit_status = WEXITSTATUS(status);
848 status_cstr = "EXITED";
849 exited = true;
850 }
851 else if (WIFSIGNALED(status))
852 {
853 signal = WTERMSIG(status);
854 status_cstr = "SIGNALED";
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000855 if (wait_pid == m_child_pid) {
Pavel Labath1107b5a2015-04-17 14:07:49 +0000856 exited = true;
857 exit_status = -1;
858 }
859 }
860 else
861 status_cstr = "(\?\?\?)";
862
863 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000864 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
Pavel Labath1107b5a2015-04-17 14:07:49 +0000865 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000866 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000867
868 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
869 }
870}
871
872bool
873NativeProcessLinux::Monitor::HandleCommands()
874{
875 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
876
877 while (true)
878 {
879 char command = 0;
880 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
881 if (size == -1)
882 {
883 if (errno == EAGAIN || errno == EWOULDBLOCK)
884 return false;
885 if (errno == EINTR)
886 continue;
887 if (log)
888 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
889 return true;
890 }
891 if (size == 0) // end of file - write end closed
892 {
893 if (log)
894 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000895 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000896 return true; // We are done.
897 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000898
899 switch (command)
900 {
901 case operation_command:
902 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000903 break;
904 case begin_block_command:
905 ++m_operation_nesting_level;
906 break;
907 case end_block_command:
908 assert(m_operation_nesting_level > 0);
909 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000910 break;
911 default:
912 if (log)
913 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
914 __FUNCTION__, command);
915 }
Pavel Labath45f5cb32015-05-05 15:05:50 +0000916
917 // notify calling thread that the command has been processed
918 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000919 }
920}
921
922void
923NativeProcessLinux::Monitor::MainLoop()
924{
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000925 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
926 m_initial_operation_up.reset();
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000927 m_child_pid = child_pid;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000928 sem_post(&m_operation_sem);
929
Pavel Labath1107b5a2015-04-17 14:07:49 +0000930 while (true)
931 {
932 fd_set fds;
933 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000934 // Only process waitpid events if we are outside of an operation block. Any pending
935 // events will be processed after we leave the block.
936 if (m_operation_nesting_level == 0)
937 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000938 FD_SET(m_pipefd[READ], &fds);
939
940 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
941 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
942 if (r < 0)
943 {
944 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
945 if (log)
946 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
947 __FUNCTION__, strerror(errno));
948 return;
949 }
950
951 if (FD_ISSET(m_pipefd[READ], &fds))
952 {
953 if (HandleCommands())
954 return;
955 }
956
957 if (FD_ISSET(m_signal_fd, &fds))
958 {
959 HandleSignals();
960 HandleWait();
961 }
962 }
963}
964
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000965Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000966NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000967{
968 Error error;
969 while (sem_wait(&m_operation_sem) != 0)
970 {
971 if (errno == EINTR)
972 continue;
973
974 error.SetErrorToErrno();
975 return error;
976 }
977
978 return m_operation_error;
979}
980
Pavel Labath1107b5a2015-04-17 14:07:49 +0000981void *
982NativeProcessLinux::Monitor::RunMonitor(void *arg)
983{
984 static_cast<Monitor *>(arg)->MainLoop();
985 return nullptr;
986}
987
988
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000989NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000990 char const **argv,
991 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000992 const FileSpec &stdin_file_spec,
993 const FileSpec &stdout_file_spec,
994 const FileSpec &stderr_file_spec,
995 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000996 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000997 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000998 m_argv(argv),
999 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +00001000 m_stdin_file_spec(stdin_file_spec),
1001 m_stdout_file_spec(stdout_file_spec),
1002 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001003 m_working_dir(working_dir),
1004 m_launch_info(launch_info)
1005{
1006}
Todd Fialaaf245d12014-06-30 21:05:18 +00001007
1008NativeProcessLinux::LaunchArgs::~LaunchArgs()
1009{ }
1010
Todd Fialaaf245d12014-06-30 21:05:18 +00001011// -----------------------------------------------------------------------------
1012// Public Static Methods
1013// -----------------------------------------------------------------------------
1014
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001015Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001016NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001017 Module *exe_module,
1018 ProcessLaunchInfo &launch_info,
1019 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001020 NativeProcessProtocolSP &native_process_sp)
1021{
1022 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1023
1024 Error error;
1025
1026 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +00001027 FileSpec working_dir{launch_info.GetWorkingDirectory()};
1028 if (working_dir &&
1029 (!working_dir.ResolvePath() ||
1030 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +00001031 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001032 error.SetErrorStringWithFormat ("No such file or directory: %s",
1033 working_dir.GetCString());
1034 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001035 }
1036
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001037 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001038
Chaoren Lind3173f32015-05-29 19:52:29 +00001039 // Default of empty will mean to use existing open file descriptors.
1040 FileSpec stdin_file_spec{};
1041 FileSpec stdout_file_spec{};
1042 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
1044 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001045 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +00001046 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +00001047
1048 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001049 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +00001050 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +00001051
1052 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001053 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +00001054 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +00001055
1056 if (log)
1057 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001058 if (stdin_file_spec)
1059 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
1060 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +00001061 else
1062 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1063
Chaoren Lind3173f32015-05-29 19:52:29 +00001064 if (stdout_file_spec)
1065 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
1066 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +00001067 else
1068 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1069
Chaoren Lind3173f32015-05-29 19:52:29 +00001070 if (stderr_file_spec)
1071 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
1072 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +00001073 else
1074 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1075 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001076
1077 // Create the NativeProcessLinux in launch mode.
1078 native_process_sp.reset (new NativeProcessLinux ());
1079
1080 if (log)
1081 {
1082 int i = 0;
1083 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1084 {
1085 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1086 ++i;
1087 }
1088 }
1089
1090 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1091 {
1092 native_process_sp.reset ();
1093 error.SetErrorStringWithFormat ("failed to register the native delegate");
1094 return error;
1095 }
1096
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001097 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001098 exe_module,
1099 launch_info.GetArguments ().GetConstArgumentVector (),
1100 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +00001101 stdin_file_spec,
1102 stdout_file_spec,
1103 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +00001104 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001105 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001106 error);
1107
1108 if (error.Fail ())
1109 {
1110 native_process_sp.reset ();
1111 if (log)
1112 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1113 return error;
1114 }
1115
1116 launch_info.SetProcessID (native_process_sp->GetID ());
1117
1118 return error;
1119}
1120
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001121Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001122NativeProcessLinux::AttachToProcess (
1123 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001124 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001125 NativeProcessProtocolSP &native_process_sp)
1126{
1127 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1128 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1129 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1130
1131 // Grab the current platform architecture. This should be Linux,
1132 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001133 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001134 if (!platform_sp)
1135 return Error("failed to get a valid default platform");
1136
1137 // Retrieve the architecture for the running process.
1138 ArchSpec process_arch;
1139 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1140 if (!error.Success ())
1141 return error;
1142
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001143 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001144
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001145 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001146 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001147 error.SetErrorStringWithFormat ("failed to register the native delegate");
1148 return error;
1149 }
1150
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001151 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001152 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001153 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001154
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001155 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001156 return error;
1157}
1158
1159// -----------------------------------------------------------------------------
1160// Public Instance Methods
1161// -----------------------------------------------------------------------------
1162
1163NativeProcessLinux::NativeProcessLinux () :
1164 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1165 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001166 m_supports_mem_region (eLazyBoolCalculate),
1167 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001168 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001169{
1170}
1171
1172//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001173// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1174// Refer to Monitor and Operation classes to see why this is necessary.
1175//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001176void
1177NativeProcessLinux::LaunchInferior (
1178 Module *module,
1179 const char *argv[],
1180 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +00001181 const FileSpec &stdin_file_spec,
1182 const FileSpec &stdout_file_spec,
1183 const FileSpec &stderr_file_spec,
1184 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001185 const ProcessLaunchInfo &launch_info,
1186 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001187{
1188 if (module)
1189 m_arch = module->GetArchitecture ();
1190
Chaoren Linfa03ad22015-02-03 01:50:42 +00001191 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001192
1193 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +00001194 new LaunchArgs(module, argv, envp,
1195 stdin_file_spec,
1196 stdout_file_spec,
1197 stderr_file_spec,
1198 working_dir,
1199 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001200
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001201 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001202 if (!error.Success ())
1203 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001204}
1205
1206void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001207NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001208{
1209 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1210 if (log)
1211 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1212
1213 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001214 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001215 if (!platform_sp)
1216 {
1217 if (log)
1218 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1219 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001220 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001221 }
1222
1223 // Gather info about the process.
1224 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001225 if (!platform_sp->GetProcessInfo (pid, process_info))
1226 {
1227 if (log)
1228 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1229 error.SetErrorString ("failed to get process info");
1230 return;
1231 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001232
1233 // Resolve the executable module
1234 ModuleSP exe_module_sp;
1235 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001236 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001237 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001238 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001239 if (!error.Success())
1240 return;
1241
1242 // Set the architecture to the exe architecture.
1243 m_arch = exe_module_sp->GetArchitecture();
1244 if (log)
1245 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1246
1247 m_pid = pid;
1248 SetState(eStateAttaching);
1249
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001250 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001251 if (!error.Success ())
1252 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001253}
1254
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001255void
1256NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001257{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001258 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001259}
1260
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001261::pid_t
1262NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001263{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001264 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001265
1266 const char **argv = args->m_argv;
1267 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +00001268 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +00001269
1270 lldb_utility::PseudoTerminal terminal;
1271 const size_t err_len = 1024;
1272 char err_str[err_len];
1273 lldb::pid_t pid;
1274 NativeThreadProtocolSP thread_sp;
1275
1276 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001277
1278 // Propagate the environment if one is not supplied.
1279 if (envp == NULL || envp[0] == NULL)
1280 envp = const_cast<const char **>(environ);
1281
1282 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1283 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001284 error.SetErrorToGenericError();
1285 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1286 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001287 }
1288
1289 // Recognized child exit status codes.
1290 enum {
1291 ePtraceFailed = 1,
1292 eDupStdinFailed,
1293 eDupStdoutFailed,
1294 eDupStderrFailed,
1295 eChdirFailed,
1296 eExecFailed,
1297 eSetGidFailed
1298 };
1299
1300 // Child process.
1301 if (pid == 0)
1302 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001303 // FIXME consider opening a pipe between parent/child and have this forked child
1304 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001305
Todd Fiala75f47c32014-10-11 21:42:09 +00001306 // Start tracing this child that is about to exec.
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001307 NativeProcessLinux::PtraceWrapper(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001308 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001309 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001310
Pavel Labath493c3a12015-02-04 10:36:57 +00001311 // terminal has already dupped the tty descriptors to stdin/out/err.
1312 // This closes original fd from which they were copied (and avoids
1313 // leaking descriptors to the debugged process.
1314 terminal.CloseSlaveFileDescriptor();
1315
Todd Fialaaf245d12014-06-30 21:05:18 +00001316 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001317 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001318 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001319
1320 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001321 if (setpgid(0, 0) != 0)
1322 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001323 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001324 // Don't allow this to prevent an inferior exec.
1325 }
1326
1327 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +00001328 if (args->m_stdin_file_spec)
1329 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001330 exit(eDupStdinFailed);
1331
Chaoren Lind3173f32015-05-29 19:52:29 +00001332 if (args->m_stdout_file_spec)
1333 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001334 exit(eDupStdoutFailed);
1335
Chaoren Lind3173f32015-05-29 19:52:29 +00001336 if (args->m_stderr_file_spec)
1337 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001338 exit(eDupStderrFailed);
1339
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001340 // Close everything besides stdin, stdout, and stderr that has no file
1341 // action to avoid leaking
1342 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1343 if (!args->m_launch_info.GetFileActionForFD(fd))
1344 close(fd);
1345
Todd Fialaaf245d12014-06-30 21:05:18 +00001346 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +00001347 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +00001348 exit(eChdirFailed);
1349
Todd Fiala0bce1b62014-08-17 00:10:50 +00001350 // Disable ASLR if requested.
1351 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1352 {
1353 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1354 if (old_personality == -1)
1355 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001356 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001357 }
1358 else
1359 {
1360 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1361 if (new_personality == -1)
1362 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001363 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001364 }
1365 else
1366 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001367 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001368 }
1369 }
1370 }
1371
Todd Fiala75f47c32014-10-11 21:42:09 +00001372 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001373 execve(argv[0],
1374 const_cast<char *const *>(argv),
1375 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001376
1377 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001378 exit(eExecFailed);
1379 }
1380
Todd Fiala75f47c32014-10-11 21:42:09 +00001381 //
1382 // This is the parent code here.
1383 //
1384 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1385
Todd Fialaaf245d12014-06-30 21:05:18 +00001386 // Wait for the child process to trap on its call to execve.
1387 ::pid_t wpid;
1388 int status;
1389 if ((wpid = waitpid(pid, &status, 0)) < 0)
1390 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001391 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001392 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001393 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1394 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001395
1396 // Mark the inferior as invalid.
1397 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001398 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001399
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001400 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001401 }
1402 else if (WIFEXITED(status))
1403 {
1404 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001405 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001406 switch (WEXITSTATUS(status))
1407 {
1408 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001409 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001410 break;
1411 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001412 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001413 break;
1414 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001415 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001416 break;
1417 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001418 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001419 break;
1420 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001421 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001422 break;
1423 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001424 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001425 break;
1426 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001427 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001428 break;
1429 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001430 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001431 break;
1432 }
1433
1434 if (log)
1435 {
1436 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1437 __FUNCTION__,
1438 WEXITSTATUS(status));
1439 }
1440
1441 // Mark the inferior as invalid.
1442 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001443 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001444
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001445 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001446 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001447 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001448 "Could not sync with inferior process.");
1449
1450 if (log)
1451 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1452
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001453 error = SetDefaultPtraceOpts(pid);
1454 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001455 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001456 if (log)
1457 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001458 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001459
1460 // Mark the inferior as invalid.
1461 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001462 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001463
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001464 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001465 }
1466
1467 // Release the master terminal descriptor and pass it off to the
1468 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001469 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1470 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001471
1472 // Set the terminal fd to be in non blocking mode (it simplifies the
1473 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1474 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001475 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1476 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001477 {
1478 if (log)
1479 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001480 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001481
1482 // Mark the inferior as invalid.
1483 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001484 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001485
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001486 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001487 }
1488
1489 if (log)
1490 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1491
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001492 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001493 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001494 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001495 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001496
1497 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001498 SetCurrentThreadID (thread_sp->GetID ());
1499 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001500
Todd Fialaaf245d12014-06-30 21:05:18 +00001501 if (log)
1502 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001503 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001504 {
1505 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1506 }
1507 else
1508 {
1509 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001510 __FUNCTION__, error.AsCString ());
1511 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001512 }
1513 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001514 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001515}
1516
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001517::pid_t
1518NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001519{
Todd Fialaaf245d12014-06-30 21:05:18 +00001520 lldb::ThreadSP inferior;
1521 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1522
1523 // Use a map to keep track of the threads which we have attached/need to attach.
1524 Host::TidMap tids_to_attach;
1525 if (pid <= 1)
1526 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001527 error.SetErrorToGenericError();
1528 error.SetErrorString("Attaching to process 1 is not allowed.");
1529 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001530 }
1531
1532 while (Host::FindProcessThreads(pid, tids_to_attach))
1533 {
1534 for (Host::TidMap::iterator it = tids_to_attach.begin();
1535 it != tids_to_attach.end();)
1536 {
1537 if (it->second == false)
1538 {
1539 lldb::tid_t tid = it->first;
1540
1541 // Attach to the requested process.
1542 // An attach will cause the thread to stop with a SIGSTOP.
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001543 NativeProcessLinux::PtraceWrapper(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001544 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001545 {
1546 // No such thread. The thread may have exited.
1547 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001548 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001549 {
1550 it = tids_to_attach.erase(it);
1551 continue;
1552 }
1553 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001554 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001555 }
1556
1557 int status;
1558 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1559 // At this point we should have a thread stopped if waitpid succeeds.
1560 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1561 {
1562 // No such thread. The thread may have exited.
1563 // More error handling may be needed.
1564 if (errno == ESRCH)
1565 {
1566 it = tids_to_attach.erase(it);
1567 continue;
1568 }
1569 else
1570 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001571 error.SetErrorToErrno();
1572 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001573 }
1574 }
1575
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001576 error = SetDefaultPtraceOpts(tid);
1577 if (error.Fail())
1578 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001579
1580 if (log)
1581 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1582
1583 it->second = true;
1584
1585 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001586 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001587 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001588
1589 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001590 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001591 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001592 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001593 }
1594
1595 // move the loop forward
1596 ++it;
1597 }
1598 }
1599
1600 if (tids_to_attach.size() > 0)
1601 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001602 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001603 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001604 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001605 }
1606 else
1607 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001608 error.SetErrorToGenericError();
1609 error.SetErrorString("No such process.");
1610 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001611 }
1612
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001613 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001614}
1615
Chaoren Lin97ccc292015-02-03 01:51:12 +00001616Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001617NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1618{
1619 long ptrace_opts = 0;
1620
1621 // Have the child raise an event on exit. This is used to keep the child in
1622 // limbo until it is destroyed.
1623 ptrace_opts |= PTRACE_O_TRACEEXIT;
1624
1625 // Have the tracer trace threads which spawn in the inferior process.
1626 // TODO: if we want to support tracing the inferiors' child, add the
1627 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1628 ptrace_opts |= PTRACE_O_TRACECLONE;
1629
1630 // Have the tracer notify us before execve returns
1631 // (needed to disable legacy SIGTRAP generation)
1632 ptrace_opts |= PTRACE_O_TRACEEXEC;
1633
Chaoren Lin97ccc292015-02-03 01:51:12 +00001634 Error error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001635 NativeProcessLinux::PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001636 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001637}
1638
1639static ExitType convert_pid_status_to_exit_type (int status)
1640{
1641 if (WIFEXITED (status))
1642 return ExitType::eExitTypeExit;
1643 else if (WIFSIGNALED (status))
1644 return ExitType::eExitTypeSignal;
1645 else if (WIFSTOPPED (status))
1646 return ExitType::eExitTypeStop;
1647 else
1648 {
1649 // We don't know what this is.
1650 return ExitType::eExitTypeInvalid;
1651 }
1652}
1653
1654static int convert_pid_status_to_return_code (int status)
1655{
1656 if (WIFEXITED (status))
1657 return WEXITSTATUS (status);
1658 else if (WIFSIGNALED (status))
1659 return WTERMSIG (status);
1660 else if (WIFSTOPPED (status))
1661 return WSTOPSIG (status);
1662 else
1663 {
1664 // We don't know what this is.
1665 return ExitType::eExitTypeInvalid;
1666 }
1667}
1668
Pavel Labath1107b5a2015-04-17 14:07:49 +00001669// Handles all waitpid events from the inferior process.
1670void
1671NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001672 bool exited,
1673 int signal,
1674 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001675{
1676 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1677
Todd Fialaaf245d12014-06-30 21:05:18 +00001678 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001679 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001680
1681 // Handle when the thread exits.
1682 if (exited)
1683 {
1684 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001685 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 +00001686
1687 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001688 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001689
1690 if (is_main_thread)
1691 {
1692 // We only set the exit status and notify the delegate if we haven't already set the process
1693 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1694 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001695 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001696 if (!already_notified)
1697 {
1698 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001699 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 +00001700 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001701 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001702
1703 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001704 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001705 }
1706 else
1707 {
1708 if (log)
1709 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1710 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001711 }
1712 else
1713 {
1714 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1715 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1716 // and we would have done an all-stop then.
1717 if (log)
1718 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 +00001719 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001720 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001721 }
1722
1723 // Get details on the signal raised.
1724 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001725 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001726 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001727 {
1728 // We have retrieved the signal info. Dispatch appropriately.
1729 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001730 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001731 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001732 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001733 }
1734 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001735 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001736 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001738 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001739 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1740 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1741 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1742 // generally not needed (one use case is debugging background task being managed by a
1743 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1744 // stop which happens before the group stop. This done by MonitorSignal and works
1745 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001746 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001747 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
1748 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001749 }
1750 else
1751 {
1752 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1753
1754 // A return value of ESRCH means the thread/process is no longer on the system,
1755 // so it was killed somehow outside of our control. Either way, we can't do anything
1756 // with it anymore.
1757
Todd Fialaaf245d12014-06-30 21:05:18 +00001758 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001759 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001760
1761 if (log)
1762 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001763 __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 +00001764
1765 if (is_main_thread)
1766 {
1767 // Notify the delegate - our process is not available but appears to have been killed outside
1768 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001769 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1770 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 }
1772 else
1773 {
1774 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1775 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001776 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 +00001777 }
1778 }
1779 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001780}
1781
1782void
Pavel Labath426bdf82015-04-28 07:51:52 +00001783NativeProcessLinux::WaitForNewThread(::pid_t tid)
1784{
1785 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1786
1787 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1788
1789 if (new_thread_sp)
1790 {
1791 // We are already tracking the thread - we got the event on the new thread (see
1792 // MonitorSignal) before this one. We are done.
1793 return;
1794 }
1795
1796 // The thread is not tracked yet, let's wait for it to appear.
1797 int status = -1;
1798 ::pid_t wait_pid;
1799 do
1800 {
1801 if (log)
1802 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1803 wait_pid = waitpid(tid, &status, __WALL);
1804 }
1805 while (wait_pid == -1 && errno == EINTR);
1806 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1807 // some checks just in case.
1808 if (wait_pid != tid) {
1809 if (log)
1810 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1811 // The only way I know of this could happen is if the whole process was
1812 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1813 return;
1814 }
1815 if (WIFEXITED(status))
1816 {
1817 if (log)
1818 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1819 // Also a very improbable event.
1820 return;
1821 }
1822
1823 siginfo_t info;
1824 Error error = GetSignalInfo(tid, &info);
1825 if (error.Fail())
1826 {
1827 if (log)
1828 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1829 return;
1830 }
1831
1832 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1833 {
1834 // We should be getting a thread creation signal here, but we received something
1835 // else. There isn't much we can do about it now, so we will just log that. Since the
1836 // thread is alive and we are receiving events from it, we shall pretend that it was
1837 // created properly.
1838 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);
1839 }
1840
1841 if (log)
1842 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1843 __FUNCTION__, GetID (), tid);
1844
1845 new_thread_sp = AddThread(tid);
1846 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1847 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001848 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001849}
1850
1851void
Todd Fialaaf245d12014-06-30 21:05:18 +00001852NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1853{
1854 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1855 const bool is_main_thread = (pid == GetID ());
1856
1857 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1858 if (!info)
1859 return;
1860
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001861 Mutex::Locker locker (m_threads_mutex);
1862
Todd Fialaaf245d12014-06-30 21:05:18 +00001863 // See if we can find a thread for this signal.
1864 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1865 if (!thread_sp)
1866 {
1867 if (log)
1868 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1869 }
1870
1871 switch (info->si_code)
1872 {
1873 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1874 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1875 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1876
1877 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1878 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001879 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001880 // creation.
1881 // We don't want to do anything with the parent thread so we just resume it. In case we
1882 // want to implement "break on thread creation" functionality, we would need to stop
1883 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001884
Pavel Labath426bdf82015-04-28 07:51:52 +00001885 unsigned long event_message = 0;
1886 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001887 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001888 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001889 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 +00001890 } else
1891 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001892
Pavel Labath5fd24c62015-04-23 09:04:35 +00001893 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001894 break;
1895 }
1896
1897 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001898 {
1899 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001900 if (log)
1901 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001902
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001903 // Exec clears any pending notifications.
1904 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001905
1906 // 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 +00001907 if (log)
1908 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1909
1910 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001911 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001912 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1913 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001914 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001915 main_thread_sp = thread_sp;
1916 if (log)
1917 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001918 }
1919 else
1920 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001921 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001922 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001923 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001924 }
1925 }
1926
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001927 m_threads.clear ();
1928
1929 if (main_thread_sp)
1930 {
1931 m_threads.push_back (main_thread_sp);
1932 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001933 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001934 }
1935 else
1936 {
1937 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1938 if (log)
1939 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1940 }
1941
Chaoren Linfa03ad22015-02-03 01:50:42 +00001942 // Tell coordinator about about the "new" (since exec) stopped main thread.
1943 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001944 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001945
1946 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1947 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001948 // Let our delegate know we have just exec'd.
1949 NotifyDidExec ();
1950
1951 // If we have a main thread, indicate we are stopped.
1952 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001953
1954 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001955 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001956
Todd Fialaaf245d12014-06-30 21:05:18 +00001957 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001958 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001959
1960 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1961 {
1962 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001963 // We don't want to do anything with the thread so we just resume it. In case we
1964 // want to implement "break on thread exit" functionality, we would need to stop
1965 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001966
Todd Fialaaf245d12014-06-30 21:05:18 +00001967 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001968 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001969 data = -1;
1970
1971 if (log)
1972 {
1973 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1974 __FUNCTION__,
1975 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1976 pid,
1977 is_main_thread ? "is main thread" : "not main thread");
1978 }
1979
Todd Fialaaf245d12014-06-30 21:05:18 +00001980 if (is_main_thread)
1981 {
1982 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001983 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001984
Pavel Labath6e351632015-05-15 13:30:59 +00001985 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001986
1987 break;
1988 }
1989
1990 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001991 case TRAP_TRACE: // We receive this on single stepping.
1992 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001993 if (thread_sp)
1994 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001995 // If a watchpoint was hit, report it
1996 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001997 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001998 if (error.Fail() && log)
1999 log->Printf("NativeProcessLinux::%s() "
2000 "received error while checking for watchpoint hits, "
2001 "pid = %" PRIu64 " error = %s",
2002 __FUNCTION__, pid, error.AsCString());
2003 if (wp_index != LLDB_INVALID_INDEX32)
2004 {
2005 MonitorWatchpoint(pid, thread_sp, wp_index);
2006 break;
2007 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002008 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002009 // Otherwise, report step over
2010 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002011 break;
2012
2013 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00002014#if defined __mips__
2015 // For mips there is no special signal for watchpoint
2016 // So we check for watchpoint in kernel trap
2017 if (thread_sp)
2018 {
2019 // If a watchpoint was hit, report it
2020 uint32_t wp_index;
2021 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, NULL);
2022 if (error.Fail() && log)
2023 log->Printf("NativeProcessLinux::%s() "
2024 "received error while checking for watchpoint hits, "
2025 "pid = %" PRIu64 " error = %s",
2026 __FUNCTION__, pid, error.AsCString());
2027 if (wp_index != LLDB_INVALID_INDEX32)
2028 {
2029 MonitorWatchpoint(pid, thread_sp, wp_index);
2030 break;
2031 }
2032 }
2033 // NO BREAK
2034#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00002035 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002036 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002037 break;
2038
2039 case SIGTRAP:
2040 case (SIGTRAP | 0x80):
2041 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002042 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2043
Todd Fialaaf245d12014-06-30 21:05:18 +00002044 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00002045 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002046 break;
2047
2048 default:
2049 assert(false && "Unexpected SIGTRAP code!");
2050 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00002051 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
2052 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00002053 break;
2054
2055 }
2056}
2057
2058void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002059NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2060{
2061 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2062 if (log)
2063 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2064 __FUNCTION__, pid);
2065
2066 if (thread_sp)
2067 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2068
2069 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002070 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002071
2072 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2073 // This would have already happened at the time the Resume() with step operation was signaled.
2074 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2075 // once all running threads have checked in as stopped.
2076 SetCurrentThreadID(pid);
2077 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00002078 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002079}
2080
2081void
2082NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2083{
2084 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2085 if (log)
2086 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2087 __FUNCTION__, pid);
2088
2089 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002090 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002091
2092 // Mark the thread as stopped at breakpoint.
2093 if (thread_sp)
2094 {
2095 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2096 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2097 if (error.Fail())
2098 if (log)
2099 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2100 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002101
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002102 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002103 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002104 }
2105 else
2106 if (log)
2107 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2108 "warning, cannot process software breakpoint since no thread metadata",
2109 __FUNCTION__, pid);
2110
2111
2112 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002113 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002114}
2115
2116void
2117NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2118{
2119 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2120 if (log)
2121 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2122 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2123 __FUNCTION__, pid, wp_index);
2124
2125 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002126 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002127
2128 // Mark the thread as stopped at watchpoint.
2129 // The address is at (lldb::addr_t)info->si_addr if we need it.
2130 lldbassert(thread_sp && "thread_sp cannot be NULL");
2131 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2132
2133 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002134 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002135}
2136
2137void
Todd Fialaaf245d12014-06-30 21:05:18 +00002138NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2139{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002140 assert (info && "null info");
2141 if (!info)
2142 return;
2143
2144 const int signo = info->si_signo;
2145 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002146
2147 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2148
2149 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2150 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2151 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2152 //
2153 // IOW, user generated signals never generate what we consider to be a
2154 // "crash".
2155 //
2156 // Similarly, ACK signals generated by this monitor.
2157
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002158 Mutex::Locker locker (m_threads_mutex);
2159
Todd Fialaaf245d12014-06-30 21:05:18 +00002160 // See if we can find a thread for this signal.
2161 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2162 if (!thread_sp)
2163 {
2164 if (log)
2165 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2166 }
2167
2168 // Handle the signal.
2169 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2170 {
2171 if (log)
2172 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2173 __FUNCTION__,
2174 GetUnixSignals ().GetSignalAsCString (signo),
2175 signo,
2176 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2177 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002178 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002179 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002180 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002181
Todd Fiala58a2f662014-08-12 17:02:07 +00002182 // Check for new thread notification.
2183 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2184 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002185 // A new thread creation is being signaled. This is one of two parts that come in
2186 // a non-deterministic order. This code handles the case where the new thread event comes
2187 // before the event on the parent thread. For the opposite case see code in
2188 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002189 if (log)
2190 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2191 __FUNCTION__, GetID (), pid);
2192
Pavel Labath5fd24c62015-04-23 09:04:35 +00002193 thread_sp = AddThread(pid);
2194 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2195 // We can now resume the newly created thread.
2196 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2197 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002198 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002199 // Done handling.
2200 return;
2201 }
2202
2203 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002204 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002205 {
2206 // This is a tgkill()-based stop.
2207 if (thread_sp)
2208 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002209 if (log)
2210 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2211 __FUNCTION__,
2212 GetID (),
2213 pid);
2214
Chaoren Linaab58632015-02-03 01:50:57 +00002215 // Check that we're not already marked with a stop reason.
2216 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2217 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2218 // and that, without an intervening resume, we received another stop. It is more likely
2219 // that we are missing the marking of a run state somewhere if we find that the thread was
2220 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002221 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2222 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002223
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002224 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002225 if (!StateIsStoppedState (thread_state, false))
2226 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002227 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2228 // Generally, these are not important stops and we don't want to report them as
2229 // they are just used to stop other threads when one thread (the one with the
2230 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2231 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2232 // leave the signal intact if this is the thread that was chosen as the
2233 // triggering thread.
2234 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002235 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002236 else
2237 linux_thread_sp->SetStoppedBySignal(0);
2238
Chaoren Linaab58632015-02-03 01:50:57 +00002239 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002240 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002241 }
2242 else
2243 {
2244 if (log)
2245 {
2246 // Retrieve the signal name if the thread was stopped by a signal.
2247 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002248 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002249 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2250 if (!signal_name)
2251 signal_name = "<no-signal-name>";
2252
2253 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",
2254 __FUNCTION__,
2255 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002256 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002257 StateAsCString (thread_state),
2258 stop_signo,
2259 signal_name);
2260 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002261 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002262 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002263 }
2264
2265 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002266 return;
2267 }
2268
2269 if (log)
2270 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2271
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002272 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002273 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002274
Pavel Labathc4e25c92015-05-29 10:13:03 +00002275 if (thread_sp)
2276 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002277
2278 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002279 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002280}
2281
Tamas Berghammere7708682015-04-22 10:00:23 +00002282namespace {
2283
2284struct EmulatorBaton
2285{
2286 NativeProcessLinux* m_process;
2287 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002288
Pavel Labath6648fcc2015-04-27 09:21:14 +00002289 // eRegisterKindDWARF -> RegsiterValue
2290 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2291
2292 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002293 m_process(process), m_reg_context(reg_context) {}
2294};
2295
2296} // anonymous namespace
2297
2298static size_t
2299ReadMemoryCallback (EmulateInstruction *instruction,
2300 void *baton,
2301 const EmulateInstruction::Context &context,
2302 lldb::addr_t addr,
2303 void *dst,
2304 size_t length)
2305{
2306 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2307
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002308 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002309 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2310 return bytes_read;
2311}
2312
2313static bool
2314ReadRegisterCallback (EmulateInstruction *instruction,
2315 void *baton,
2316 const RegisterInfo *reg_info,
2317 RegisterValue &reg_value)
2318{
2319 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2320
Pavel Labath6648fcc2015-04-27 09:21:14 +00002321 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2322 if (it != emulator_baton->m_register_values.end())
2323 {
2324 reg_value = it->second;
2325 return true;
2326 }
2327
Tamas Berghammere7708682015-04-22 10:00:23 +00002328 // The emulator only fill in the dwarf regsiter numbers (and in some case
2329 // the generic register numbers). Get the full register info from the
2330 // register context based on the dwarf register numbers.
2331 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2332 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2333
2334 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002335 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002336 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002337
Pavel Labath6648fcc2015-04-27 09:21:14 +00002338 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002339}
2340
2341static bool
2342WriteRegisterCallback (EmulateInstruction *instruction,
2343 void *baton,
2344 const EmulateInstruction::Context &context,
2345 const RegisterInfo *reg_info,
2346 const RegisterValue &reg_value)
2347{
2348 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002349 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002350 return true;
2351}
2352
2353static size_t
2354WriteMemoryCallback (EmulateInstruction *instruction,
2355 void *baton,
2356 const EmulateInstruction::Context &context,
2357 lldb::addr_t addr,
2358 const void *dst,
2359 size_t length)
2360{
2361 return length;
2362}
2363
2364static lldb::addr_t
2365ReadFlags (NativeRegisterContext* regsiter_context)
2366{
2367 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2368 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2369 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2370}
2371
2372Error
2373NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2374{
2375 Error error;
2376 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2377
2378 std::unique_ptr<EmulateInstruction> emulator_ap(
2379 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2380
2381 if (emulator_ap == nullptr)
2382 return Error("Instruction emulator not found!");
2383
2384 EmulatorBaton baton(this, register_context_sp.get());
2385 emulator_ap->SetBaton(&baton);
2386 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2387 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2388 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2389 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2390
2391 if (!emulator_ap->ReadInstruction())
2392 return Error("Read instruction failed!");
2393
Pavel Labath6648fcc2015-04-27 09:21:14 +00002394 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2395
2396 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2397 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2398
2399 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2400 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2401
Tamas Berghammere7708682015-04-22 10:00:23 +00002402 lldb::addr_t next_pc;
2403 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002404 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002405 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002406 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2407 next_pc = pc_it->second.GetAsUInt64();
2408
2409 if (flags_it != baton.m_register_values.end())
2410 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002411 else
2412 next_flags = ReadFlags (register_context_sp.get());
2413 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002414 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002415 {
2416 // Emulate instruction failed and it haven't changed PC. Advance PC
2417 // with the size of the current opcode because the emulation of all
2418 // PC modifying instruction should be successful. The failure most
2419 // likely caused by a not supported instruction which don't modify PC.
2420 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2421 next_flags = ReadFlags (register_context_sp.get());
2422 }
2423 else
2424 {
2425 // The instruction emulation failed after it modified the PC. It is an
2426 // unknown error where we can't continue because the next instruction is
2427 // modifying the PC but we don't know how.
2428 return Error ("Instruction emulation failed unexpectedly.");
2429 }
2430
2431 if (m_arch.GetMachine() == llvm::Triple::arm)
2432 {
2433 if (next_flags & 0x20)
2434 {
2435 // Thumb mode
2436 error = SetSoftwareBreakpoint(next_pc, 2);
2437 }
2438 else
2439 {
2440 // Arm mode
2441 error = SetSoftwareBreakpoint(next_pc, 4);
2442 }
2443 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002444 else if (m_arch.GetMachine() == llvm::Triple::mips64
2445 || m_arch.GetMachine() == llvm::Triple::mips64el)
2446 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002447 else
2448 {
2449 // No size hint is given for the next breakpoint
2450 error = SetSoftwareBreakpoint(next_pc, 0);
2451 }
2452
Tamas Berghammere7708682015-04-22 10:00:23 +00002453 if (error.Fail())
2454 return error;
2455
2456 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2457
2458 return Error();
2459}
2460
2461bool
2462NativeProcessLinux::SupportHardwareSingleStepping() const
2463{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002464 if (m_arch.GetMachine() == llvm::Triple::arm
2465 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2466 return false;
2467 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002468}
2469
Todd Fialaaf245d12014-06-30 21:05:18 +00002470Error
2471NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2472{
Todd Fialaaf245d12014-06-30 21:05:18 +00002473 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2474 if (log)
2475 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2476
Tamas Berghammere7708682015-04-22 10:00:23 +00002477 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002478
Pavel Labath45f5cb32015-05-05 15:05:50 +00002479 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002480 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002481
Tamas Berghammere7708682015-04-22 10:00:23 +00002482 if (software_single_step)
2483 {
2484 for (auto thread_sp : m_threads)
2485 {
2486 assert (thread_sp && "thread list should not contain NULL threads");
2487
2488 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2489 if (action == nullptr)
2490 continue;
2491
2492 if (action->state == eStateStepping)
2493 {
2494 Error error = SetupSoftwareSingleStepping(thread_sp);
2495 if (error.Fail())
2496 return error;
2497 }
2498 }
2499 }
2500
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002501 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002502 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002503 assert (thread_sp && "thread list should not contain NULL threads");
2504
2505 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2506
2507 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002508 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002509 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002510 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2511 __FUNCTION__, GetID (), thread_sp->GetID ());
2512 continue;
2513 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002514
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002515 if (log)
2516 {
2517 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2518 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2519 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002520
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002521 switch (action->state)
2522 {
2523 case eStateRunning:
2524 {
2525 // Run the thread, possibly feeding it the signal.
2526 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002527 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002528 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2529 {
2530 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2531 // Pass this signal number on to the inferior to handle.
2532 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2533 if (resume_result.Success())
2534 SetState(eStateRunning, true);
2535 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002536 },
2537 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002538 break;
2539 }
2540
2541 case eStateStepping:
2542 {
2543 // Request the step.
2544 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002545 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002546 [=](lldb::tid_t tid_to_step, bool supress_signal)
2547 {
2548 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002549
Pavel Labathc0765592015-05-06 10:46:34 +00002550 Error step_result;
2551 if (software_single_step)
2552 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2553 else
2554 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002555
Pavel Labathc0765592015-05-06 10:46:34 +00002556 assert (step_result.Success() && "SingleStep() failed");
2557 if (step_result.Success())
2558 SetState(eStateStepping, true);
2559 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002560 },
2561 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002562 break;
2563 }
2564
2565 case eStateSuspended:
2566 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002567 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002568
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002569 default:
2570 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2571 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002572 }
2573 }
2574
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002575 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002576}
2577
2578Error
2579NativeProcessLinux::Halt ()
2580{
2581 Error error;
2582
Todd Fialaaf245d12014-06-30 21:05:18 +00002583 if (kill (GetID (), SIGSTOP) != 0)
2584 error.SetErrorToErrno ();
2585
2586 return error;
2587}
2588
2589Error
2590NativeProcessLinux::Detach ()
2591{
2592 Error error;
2593
2594 // Tell ptrace to detach from the process.
2595 if (GetID () != LLDB_INVALID_PROCESS_ID)
2596 error = Detach (GetID ());
2597
2598 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00002599 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002600
2601 // No error.
2602 return error;
2603}
2604
2605Error
2606NativeProcessLinux::Signal (int signo)
2607{
2608 Error error;
2609
2610 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2611 if (log)
2612 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2613 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2614
2615 if (kill(GetID(), signo))
2616 error.SetErrorToErrno();
2617
2618 return error;
2619}
2620
2621Error
Chaoren Line9547b82015-02-03 01:51:00 +00002622NativeProcessLinux::Interrupt ()
2623{
2624 // Pick a running thread (or if none, a not-dead stopped thread) as
2625 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002626 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2627
2628 NativeThreadProtocolSP running_thread_sp;
2629 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002630
2631 if (log)
2632 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2633
Pavel Labath45f5cb32015-05-05 15:05:50 +00002634 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002635 Mutex::Locker locker (m_threads_mutex);
2636
2637 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002638 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002639 // The thread shouldn't be null but lets just cover that here.
2640 if (!thread_sp)
2641 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002642
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002643 // If we have a running or stepping thread, we'll call that the
2644 // target of the interrupt.
2645 const auto thread_state = thread_sp->GetState ();
2646 if (thread_state == eStateRunning ||
2647 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002648 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002649 running_thread_sp = thread_sp;
2650 break;
2651 }
2652 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2653 {
2654 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2655 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002656 }
2657 }
2658
2659 if (!running_thread_sp && !stopped_thread_sp)
2660 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002661 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002662 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002663 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002664
Chaoren Line9547b82015-02-03 01:51:00 +00002665 return error;
2666 }
2667
2668 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2669
2670 if (log)
2671 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2672 __FUNCTION__,
2673 GetID (),
2674 running_thread_sp ? "running" : "stopped",
2675 deferred_signal_thread_sp->GetID ());
2676
Pavel Labathed89c7f2015-05-06 12:22:37 +00002677 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002678
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002679 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002680}
2681
2682Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002683NativeProcessLinux::Kill ()
2684{
2685 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2686 if (log)
2687 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2688
2689 Error error;
2690
2691 switch (m_state)
2692 {
2693 case StateType::eStateInvalid:
2694 case StateType::eStateExited:
2695 case StateType::eStateCrashed:
2696 case StateType::eStateDetached:
2697 case StateType::eStateUnloaded:
2698 // Nothing to do - the process is already dead.
2699 if (log)
2700 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2701 return error;
2702
2703 case StateType::eStateConnected:
2704 case StateType::eStateAttaching:
2705 case StateType::eStateLaunching:
2706 case StateType::eStateStopped:
2707 case StateType::eStateRunning:
2708 case StateType::eStateStepping:
2709 case StateType::eStateSuspended:
2710 // We can try to kill a process in these states.
2711 break;
2712 }
2713
2714 if (kill (GetID (), SIGKILL) != 0)
2715 {
2716 error.SetErrorToErrno ();
2717 return error;
2718 }
2719
2720 return error;
2721}
2722
2723static Error
2724ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2725{
2726 memory_region_info.Clear();
2727
2728 StringExtractor line_extractor (maps_line.c_str ());
2729
2730 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2731 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2732
2733 // Parse out the starting address
2734 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2735
2736 // Parse out hyphen separating start and end address from range.
2737 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2738 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2739
2740 // Parse out the ending address
2741 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2742
2743 // Parse out the space after the address.
2744 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2745 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2746
2747 // Save the range.
2748 memory_region_info.GetRange ().SetRangeBase (start_address);
2749 memory_region_info.GetRange ().SetRangeEnd (end_address);
2750
2751 // Parse out each permission entry.
2752 if (line_extractor.GetBytesLeft () < 4)
2753 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2754
2755 // Handle read permission.
2756 const char read_perm_char = line_extractor.GetChar ();
2757 if (read_perm_char == 'r')
2758 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2759 else
2760 {
2761 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2762 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2763 }
2764
2765 // Handle write permission.
2766 const char write_perm_char = line_extractor.GetChar ();
2767 if (write_perm_char == 'w')
2768 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2769 else
2770 {
2771 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2772 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2773 }
2774
2775 // Handle execute permission.
2776 const char exec_perm_char = line_extractor.GetChar ();
2777 if (exec_perm_char == 'x')
2778 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2779 else
2780 {
2781 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2782 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2783 }
2784
2785 return Error ();
2786}
2787
2788Error
2789NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2790{
2791 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2792 // with no perms if it is not mapped.
2793
2794 // Use an approach that reads memory regions from /proc/{pid}/maps.
2795 // Assume proc maps entries are in ascending order.
2796 // FIXME assert if we find differently.
2797 Mutex::Locker locker (m_mem_region_cache_mutex);
2798
2799 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2800 Error error;
2801
2802 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2803 {
2804 // We're done.
2805 error.SetErrorString ("unsupported");
2806 return error;
2807 }
2808
2809 // If our cache is empty, pull the latest. There should always be at least one memory region
2810 // if memory region handling is supported.
2811 if (m_mem_region_cache.empty ())
2812 {
2813 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2814 [&] (const std::string &line) -> bool
2815 {
2816 MemoryRegionInfo info;
2817 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2818 if (parse_error.Success ())
2819 {
2820 m_mem_region_cache.push_back (info);
2821 return true;
2822 }
2823 else
2824 {
2825 if (log)
2826 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2827 return false;
2828 }
2829 });
2830
2831 // If we had an error, we'll mark unsupported.
2832 if (error.Fail ())
2833 {
2834 m_supports_mem_region = LazyBool::eLazyBoolNo;
2835 return error;
2836 }
2837 else if (m_mem_region_cache.empty ())
2838 {
2839 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2840 // is supported. Assume we don't support map entries via procfs.
2841 if (log)
2842 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2843 m_supports_mem_region = LazyBool::eLazyBoolNo;
2844 error.SetErrorString ("not supported");
2845 return error;
2846 }
2847
2848 if (log)
2849 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2850
2851 // We support memory retrieval, remember that.
2852 m_supports_mem_region = LazyBool::eLazyBoolYes;
2853 }
2854 else
2855 {
2856 if (log)
2857 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2858 }
2859
2860 lldb::addr_t prev_base_address = 0;
2861
2862 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2863 // There can be a ton of regions on pthreads apps with lots of threads.
2864 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2865 {
2866 MemoryRegionInfo &proc_entry_info = *it;
2867
2868 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2869 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2870 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2871
2872 // If the target address comes before this entry, indicate distance to next region.
2873 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2874 {
2875 range_info.GetRange ().SetRangeBase (load_addr);
2876 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2877 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2878 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2879 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2880
2881 return error;
2882 }
2883 else if (proc_entry_info.GetRange ().Contains (load_addr))
2884 {
2885 // The target address is within the memory region we're processing here.
2886 range_info = proc_entry_info;
2887 return error;
2888 }
2889
2890 // The target memory address comes somewhere after the region we just parsed.
2891 }
2892
2893 // If we made it here, we didn't find an entry that contained the given address.
2894 error.SetErrorString ("address comes after final region");
2895
2896 if (log)
2897 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
2898
2899 return error;
2900}
2901
2902void
2903NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2904{
2905 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2906 if (log)
2907 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2908
2909 {
2910 Mutex::Locker locker (m_mem_region_cache_mutex);
2911 if (log)
2912 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2913 m_mem_region_cache.clear ();
2914 }
2915}
2916
2917Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002918NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002919{
2920 // FIXME implementing this requires the equivalent of
2921 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2922 // functional ThreadPlans working with Native*Protocol.
2923#if 1
2924 return Error ("not implemented yet");
2925#else
2926 addr = LLDB_INVALID_ADDRESS;
2927
2928 unsigned prot = 0;
2929 if (permissions & lldb::ePermissionsReadable)
2930 prot |= eMmapProtRead;
2931 if (permissions & lldb::ePermissionsWritable)
2932 prot |= eMmapProtWrite;
2933 if (permissions & lldb::ePermissionsExecutable)
2934 prot |= eMmapProtExec;
2935
2936 // TODO implement this directly in NativeProcessLinux
2937 // (and lift to NativeProcessPOSIX if/when that class is
2938 // refactored out).
2939 if (InferiorCallMmap(this, addr, 0, size, prot,
2940 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2941 m_addr_to_mmap_size[addr] = size;
2942 return Error ();
2943 } else {
2944 addr = LLDB_INVALID_ADDRESS;
2945 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2946 }
2947#endif
2948}
2949
2950Error
2951NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2952{
2953 // FIXME see comments in AllocateMemory - required lower-level
2954 // bits not in place yet (ThreadPlans)
2955 return Error ("not implemented");
2956}
2957
2958lldb::addr_t
2959NativeProcessLinux::GetSharedLibraryInfoAddress ()
2960{
2961#if 1
2962 // punt on this for now
2963 return LLDB_INVALID_ADDRESS;
2964#else
2965 // Return the image info address for the exe module
2966#if 1
2967 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2968
2969 ModuleSP module_sp;
2970 Error error = GetExeModuleSP (module_sp);
2971 if (error.Fail ())
2972 {
2973 if (log)
2974 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2975 return LLDB_INVALID_ADDRESS;
2976 }
2977
2978 if (module_sp == nullptr)
2979 {
2980 if (log)
2981 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2982 return LLDB_INVALID_ADDRESS;
2983 }
2984
2985 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2986 if (object_file_sp == nullptr)
2987 {
2988 if (log)
2989 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2990 return LLDB_INVALID_ADDRESS;
2991 }
2992
2993 return obj_file_sp->GetImageInfoAddress();
2994#else
2995 Target *target = &GetTarget();
2996 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2997 Address addr = obj_file->GetImageInfoAddress(target);
2998
2999 if (addr.IsValid())
3000 return addr.GetLoadAddress(target);
3001 return LLDB_INVALID_ADDRESS;
3002#endif
3003#endif // punt on this for now
3004}
3005
3006size_t
3007NativeProcessLinux::UpdateThreads ()
3008{
3009 // The NativeProcessLinux monitoring threads are always up to date
3010 // with respect to thread state and they keep the thread list
3011 // populated properly. All this method needs to do is return the
3012 // thread count.
3013 Mutex::Locker locker (m_threads_mutex);
3014 return m_threads.size ();
3015}
3016
3017bool
3018NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3019{
3020 arch = m_arch;
3021 return true;
3022}
3023
3024Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003025NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003026{
3027 // FIXME put this behind a breakpoint protocol class that can be
3028 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003029 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003030 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003031 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003032
3033 switch (m_arch.GetMachine ())
3034 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003035 case llvm::Triple::aarch64:
3036 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3037 return Error ();
3038
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003039 case llvm::Triple::arm:
3040 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3041 return Error ();
3042
Todd Fialaaf245d12014-06-30 21:05:18 +00003043 case llvm::Triple::x86:
3044 case llvm::Triple::x86_64:
3045 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3046 return Error ();
3047
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003048 case llvm::Triple::mips64:
3049 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00003050 case llvm::Triple::mips:
3051 case llvm::Triple::mipsel:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003052 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3053 return Error ();
3054
Todd Fialaaf245d12014-06-30 21:05:18 +00003055 default:
3056 assert(false && "CPU type not supported!");
3057 return Error ("CPU type not supported");
3058 }
3059}
3060
3061Error
3062NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3063{
3064 if (hardware)
3065 return Error ("NativeProcessLinux does not support hardware breakpoints");
3066 else
3067 return SetSoftwareBreakpoint (addr, size);
3068}
3069
3070Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003071NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3072 size_t &actual_opcode_size,
3073 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003074{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003075 // FIXME put this behind a breakpoint protocol class that can be set per
3076 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003077 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003078 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3079 // linux kernel does otherwise.
3080 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003081 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003082 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003083 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003084 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003085
3086 switch (m_arch.GetMachine ())
3087 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003088 case llvm::Triple::aarch64:
3089 trap_opcode_bytes = g_aarch64_opcode;
3090 actual_opcode_size = sizeof(g_aarch64_opcode);
3091 return Error ();
3092
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003093 case llvm::Triple::arm:
3094 switch (trap_opcode_size_hint)
3095 {
3096 case 2:
3097 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3098 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3099 return Error ();
3100 case 4:
3101 trap_opcode_bytes = g_arm_breakpoint_opcode;
3102 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3103 return Error ();
3104 default:
3105 assert(false && "Unrecognised trap opcode size hint!");
3106 return Error ("Unrecognised trap opcode size hint!");
3107 }
3108
Todd Fialaaf245d12014-06-30 21:05:18 +00003109 case llvm::Triple::x86:
3110 case llvm::Triple::x86_64:
3111 trap_opcode_bytes = g_i386_opcode;
3112 actual_opcode_size = sizeof(g_i386_opcode);
3113 return Error ();
3114
Sagar Thakurce815e42015-06-03 10:14:24 +00003115 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003116 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003117 trap_opcode_bytes = g_mips64_opcode;
3118 actual_opcode_size = sizeof(g_mips64_opcode);
3119 return Error ();
3120
Sagar Thakurce815e42015-06-03 10:14:24 +00003121 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003122 case llvm::Triple::mips64el:
3123 trap_opcode_bytes = g_mips64el_opcode;
3124 actual_opcode_size = sizeof(g_mips64el_opcode);
3125 return Error ();
3126
Todd Fialaaf245d12014-06-30 21:05:18 +00003127 default:
3128 assert(false && "CPU type not supported!");
3129 return Error ("CPU type not supported");
3130 }
3131}
3132
3133#if 0
3134ProcessMessage::CrashReason
3135NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3136{
3137 ProcessMessage::CrashReason reason;
3138 assert(info->si_signo == SIGSEGV);
3139
3140 reason = ProcessMessage::eInvalidCrashReason;
3141
3142 switch (info->si_code)
3143 {
3144 default:
3145 assert(false && "unexpected si_code for SIGSEGV");
3146 break;
3147 case SI_KERNEL:
3148 // Linux will occasionally send spurious SI_KERNEL codes.
3149 // (this is poorly documented in sigaction)
3150 // One way to get this is via unaligned SIMD loads.
3151 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3152 break;
3153 case SEGV_MAPERR:
3154 reason = ProcessMessage::eInvalidAddress;
3155 break;
3156 case SEGV_ACCERR:
3157 reason = ProcessMessage::ePrivilegedAddress;
3158 break;
3159 }
3160
3161 return reason;
3162}
3163#endif
3164
3165
3166#if 0
3167ProcessMessage::CrashReason
3168NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3169{
3170 ProcessMessage::CrashReason reason;
3171 assert(info->si_signo == SIGILL);
3172
3173 reason = ProcessMessage::eInvalidCrashReason;
3174
3175 switch (info->si_code)
3176 {
3177 default:
3178 assert(false && "unexpected si_code for SIGILL");
3179 break;
3180 case ILL_ILLOPC:
3181 reason = ProcessMessage::eIllegalOpcode;
3182 break;
3183 case ILL_ILLOPN:
3184 reason = ProcessMessage::eIllegalOperand;
3185 break;
3186 case ILL_ILLADR:
3187 reason = ProcessMessage::eIllegalAddressingMode;
3188 break;
3189 case ILL_ILLTRP:
3190 reason = ProcessMessage::eIllegalTrap;
3191 break;
3192 case ILL_PRVOPC:
3193 reason = ProcessMessage::ePrivilegedOpcode;
3194 break;
3195 case ILL_PRVREG:
3196 reason = ProcessMessage::ePrivilegedRegister;
3197 break;
3198 case ILL_COPROC:
3199 reason = ProcessMessage::eCoprocessorError;
3200 break;
3201 case ILL_BADSTK:
3202 reason = ProcessMessage::eInternalStackError;
3203 break;
3204 }
3205
3206 return reason;
3207}
3208#endif
3209
3210#if 0
3211ProcessMessage::CrashReason
3212NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3213{
3214 ProcessMessage::CrashReason reason;
3215 assert(info->si_signo == SIGFPE);
3216
3217 reason = ProcessMessage::eInvalidCrashReason;
3218
3219 switch (info->si_code)
3220 {
3221 default:
3222 assert(false && "unexpected si_code for SIGFPE");
3223 break;
3224 case FPE_INTDIV:
3225 reason = ProcessMessage::eIntegerDivideByZero;
3226 break;
3227 case FPE_INTOVF:
3228 reason = ProcessMessage::eIntegerOverflow;
3229 break;
3230 case FPE_FLTDIV:
3231 reason = ProcessMessage::eFloatDivideByZero;
3232 break;
3233 case FPE_FLTOVF:
3234 reason = ProcessMessage::eFloatOverflow;
3235 break;
3236 case FPE_FLTUND:
3237 reason = ProcessMessage::eFloatUnderflow;
3238 break;
3239 case FPE_FLTRES:
3240 reason = ProcessMessage::eFloatInexactResult;
3241 break;
3242 case FPE_FLTINV:
3243 reason = ProcessMessage::eFloatInvalidOperation;
3244 break;
3245 case FPE_FLTSUB:
3246 reason = ProcessMessage::eFloatSubscriptRange;
3247 break;
3248 }
3249
3250 return reason;
3251}
3252#endif
3253
3254#if 0
3255ProcessMessage::CrashReason
3256NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3257{
3258 ProcessMessage::CrashReason reason;
3259 assert(info->si_signo == SIGBUS);
3260
3261 reason = ProcessMessage::eInvalidCrashReason;
3262
3263 switch (info->si_code)
3264 {
3265 default:
3266 assert(false && "unexpected si_code for SIGBUS");
3267 break;
3268 case BUS_ADRALN:
3269 reason = ProcessMessage::eIllegalAlignment;
3270 break;
3271 case BUS_ADRERR:
3272 reason = ProcessMessage::eIllegalAddress;
3273 break;
3274 case BUS_OBJERR:
3275 reason = ProcessMessage::eHardwareError;
3276 break;
3277 }
3278
3279 return reason;
3280}
3281#endif
3282
Todd Fialaaf245d12014-06-30 21:05:18 +00003283Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003284NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3285{
3286 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3287 // for it.
3288 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3289 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3290}
3291
3292Error
3293NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3294{
3295 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3296 // for it.
3297 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3298 return NativeProcessProtocol::RemoveWatchpoint(addr);
3299}
3300
3301Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003302NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003303{
Pavel Labathdf7c6992015-06-17 18:38:49 +00003304 if (ProcessVmReadvSupported()) {
3305 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3306 // this syscall if it is supported.
3307
3308 const ::pid_t pid = GetID();
3309
3310 struct iovec local_iov, remote_iov;
3311 local_iov.iov_base = buf;
3312 local_iov.iov_len = size;
3313 remote_iov.iov_base = reinterpret_cast<void *>(addr);
3314 remote_iov.iov_len = size;
3315
3316 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3317 const bool success = bytes_read == size;
3318
3319 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3320 if (log)
3321 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3322 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3323
3324 if (success)
3325 return Error();
3326 // else
3327 // the call failed for some reason, let's retry the read using ptrace api.
3328 }
3329
Todd Fialaaf245d12014-06-30 21:05:18 +00003330 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003331 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003332 return op.GetError ();
3333}
3334
3335Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003336NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3337{
3338 Error error = ReadMemory(addr, buf, size, bytes_read);
3339 if (error.Fail()) return error;
3340 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3341}
3342
3343Error
3344NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003345{
3346 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003347 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003348 return op.GetError ();
3349}
3350
Chaoren Lin97ccc292015-02-03 01:51:12 +00003351Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003352NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3353{
Todd Fialaaf245d12014-06-30 21:05:18 +00003354 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3355
3356 if (log)
3357 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3358 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003359 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003360 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003361 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003362 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3363 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003364}
3365
Chaoren Lin97ccc292015-02-03 01:51:12 +00003366Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003367NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3368{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003369 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003370 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003371 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003372}
3373
Chaoren Lin97ccc292015-02-03 01:51:12 +00003374Error
3375NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003376{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003377 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003378 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003379 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003380}
3381
Chaoren Lin97ccc292015-02-03 01:51:12 +00003382Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003383NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3384{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003385 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003386 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003387 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003388}
3389
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003390Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003391NativeProcessLinux::Detach(lldb::tid_t tid)
3392{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003393 if (tid == LLDB_INVALID_THREAD_ID)
3394 return Error();
3395
3396 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003397 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003398 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003399}
3400
3401bool
Chaoren Lind3173f32015-05-29 19:52:29 +00003402NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00003403{
Chaoren Lind3173f32015-05-29 19:52:29 +00003404 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00003405
3406 if (target_fd == -1)
3407 return false;
3408
Pavel Labath493c3a12015-02-04 10:36:57 +00003409 if (dup2(target_fd, fd) == -1)
3410 return false;
3411
3412 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003413}
3414
3415void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003416NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003417{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003418 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003419 error = m_monitor_up->Initialize();
3420 if (error.Fail()) {
3421 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003422 }
3423}
3424
Todd Fialaaf245d12014-06-30 21:05:18 +00003425bool
3426NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3427{
3428 for (auto thread_sp : m_threads)
3429 {
3430 assert (thread_sp && "thread list should not contain NULL threads");
3431 if (thread_sp->GetID () == thread_id)
3432 {
3433 // We have this thread.
3434 return true;
3435 }
3436 }
3437
3438 // We don't have this thread.
3439 return false;
3440}
3441
3442NativeThreadProtocolSP
3443NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3444{
3445 // CONSIDER organize threads by map - we can do better than linear.
3446 for (auto thread_sp : m_threads)
3447 {
3448 if (thread_sp->GetID () == thread_id)
3449 return thread_sp;
3450 }
3451
3452 // We don't have this thread.
3453 return NativeThreadProtocolSP ();
3454}
3455
3456bool
3457NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3458{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003459 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3460
3461 if (log)
3462 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3463
3464 bool found = false;
3465
Todd Fialaaf245d12014-06-30 21:05:18 +00003466 Mutex::Locker locker (m_threads_mutex);
3467 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3468 {
3469 if (*it && ((*it)->GetID () == thread_id))
3470 {
3471 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003472 found = true;
3473 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003474 }
3475 }
3476
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003477 // If we have a pending notification, remove this from the set.
3478 if (m_pending_notification_up)
3479 {
3480 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003481 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003482 }
3483
3484 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003485}
3486
3487NativeThreadProtocolSP
3488NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3489{
3490 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3491
3492 Mutex::Locker locker (m_threads_mutex);
3493
3494 if (log)
3495 {
3496 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3497 __FUNCTION__,
3498 GetID (),
3499 thread_id);
3500 }
3501
3502 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3503
3504 // If this is the first thread, save it as the current thread
3505 if (m_threads.empty ())
3506 SetCurrentThreadID (thread_id);
3507
3508 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3509 m_threads.push_back (thread_sp);
3510
3511 return thread_sp;
3512}
3513
Todd Fialaaf245d12014-06-30 21:05:18 +00003514Error
3515NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3516{
Todd Fiala75f47c32014-10-11 21:42:09 +00003517 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003518
3519 Error error;
3520
3521 // Get a linux thread pointer.
3522 if (!thread_sp)
3523 {
3524 error.SetErrorString ("null thread_sp");
3525 if (log)
3526 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3527 return error;
3528 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003529 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003530
3531 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003532 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003533 if (!context_sp)
3534 {
3535 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3536 if (log)
3537 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3538 return error;
3539 }
3540
3541 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003542 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003543 if (error.Fail ())
3544 {
3545 if (log)
3546 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3547 return error;
3548 }
3549 else
3550 {
3551 if (log)
3552 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3553 }
3554
3555 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3556 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3557 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003558 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003559 {
3560 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003561 if (breakpoint_addr >= breakpoint_size)
3562 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003563 }
3564
3565 // Check if we stopped because of a breakpoint.
3566 NativeBreakpointSP breakpoint_sp;
3567 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3568 if (!error.Success () || !breakpoint_sp)
3569 {
3570 // We didn't find one at a software probe location. Nothing to do.
3571 if (log)
3572 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3573 return Error ();
3574 }
3575
3576 // If the breakpoint is not a software breakpoint, nothing to do.
3577 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3578 {
3579 if (log)
3580 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3581 return Error ();
3582 }
3583
3584 //
3585 // We have a software breakpoint and need to adjust the PC.
3586 //
3587
3588 // Sanity check.
3589 if (breakpoint_size == 0)
3590 {
3591 // Nothing to do! How did we get here?
3592 if (log)
3593 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);
3594 return Error ();
3595 }
3596
3597 // Change the program counter.
3598 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003599 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 +00003600
3601 error = context_sp->SetPC (breakpoint_addr);
3602 if (error.Fail ())
3603 {
3604 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003605 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 +00003606 return error;
3607 }
3608
3609 return error;
3610}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003611
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003612Error
3613NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3614{
3615 char maps_file_name[32];
3616 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3617
3618 FileSpec maps_file_spec(maps_file_name, false);
3619 if (!maps_file_spec.Exists()) {
3620 file_spec.Clear();
3621 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3622 }
3623
3624 FileSpec module_file_spec(module_path, true);
3625
3626 std::ifstream maps_file(maps_file_name);
3627 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3628 StringRef maps_data(maps_data_str.c_str());
3629
3630 while (!maps_data.empty())
3631 {
3632 StringRef maps_row;
3633 std::tie(maps_row, maps_data) = maps_data.split('\n');
3634
3635 SmallVector<StringRef, 16> maps_columns;
3636 maps_row.split(maps_columns, StringRef(" "), -1, false);
3637
3638 if (maps_columns.size() >= 6)
3639 {
3640 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3641 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3642 return Error();
3643 }
3644 }
3645
3646 file_spec.Clear();
3647 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3648 module_file_spec.GetFilename().AsCString(), GetID());
3649}
Pavel Labathc0765592015-05-06 10:46:34 +00003650
Pavel Labath5eb721e2015-05-07 08:30:31 +00003651Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003652NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003653 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003654 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003655 bool error_when_already_running)
3656{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003657 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003658
3659 if (log)
3660 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3661 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003662
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003663 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3664 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003665
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003666 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003667 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003668 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003669
3670 lldbassert(!(error_when_already_running && !is_stopped));
3671
Pavel Labathc0765592015-05-06 10:46:34 +00003672 if (!is_stopped)
3673 {
3674 // It's not an error, just a log, if the error_when_already_running flag is not set.
3675 // This covers cases where, for instance, we're just trying to resume all threads
3676 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003677 if (log)
3678 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3679 __FUNCTION__,
3680 tid);
3681 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003682 }
3683
3684 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003685 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003686 // this thread to stop. This is potentially a buggy situation since
3687 // we're ostensibly waiting for threads to stop before we send out the
3688 // pending notification, and here we are resuming one before we send
3689 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003690 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003691 {
Pavel Labath108c3252015-05-12 09:03:18 +00003692 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 +00003693 }
3694
3695 // Request a resume. We expect this to be synchronous and the system
3696 // to reflect it is running after this completes.
3697 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003698 if (error.Success())
3699 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003700 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003701 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003702 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003703 __FUNCTION__, tid, error.AsCString ());
3704 }
3705
Pavel Labath5eb721e2015-05-07 08:30:31 +00003706 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003707}
3708
3709//===----------------------------------------------------------------------===//
3710
3711void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003712NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003713{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003714 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003715
Pavel Labath5eb721e2015-05-07 08:30:31 +00003716 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003717 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003718 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003719 __FUNCTION__, triggering_tid);
3720 }
3721
Pavel Labath337f3eb2015-05-08 08:57:45 +00003722 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003723
Pavel Labath5eb721e2015-05-07 08:30:31 +00003724 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003725 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003726 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003727 }
3728}
3729
3730void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003731NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003732{
3733 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3734 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003735 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3736
3737 // Clear any temporary breakpoints we used to implement software single stepping.
3738 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3739 {
3740 Error error = RemoveBreakpoint (thread_info.second);
3741 if (error.Fail())
3742 if (log)
3743 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3744 __FUNCTION__, thread_info.first, error.AsCString());
3745 }
3746 m_threads_stepping_with_breakpoint.clear();
3747
3748 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003749 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3750 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003751 m_pending_notification_up.reset();
3752 }
3753}
3754
Pavel Labathc0765592015-05-06 10:46:34 +00003755void
3756NativeProcessLinux::RequestStopOnAllRunningThreads()
3757{
3758 // Request a stop for all the thread stops that need to be stopped
3759 // and are not already known to be stopped. Keep a list of all the
3760 // threads from which we still need to hear a stop reply.
3761
3762 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003763 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003764 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003765 // We only care about running threads
3766 if (StateIsStoppedState(thread_sp->GetState(), true))
3767 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003768
Pavel Labath108c3252015-05-12 09:03:18 +00003769 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3770 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003771 }
3772
3773 // Set the wait list to the set of tids for which we requested stops.
3774 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3775}
3776
Pavel Labathc0765592015-05-06 10:46:34 +00003777
Pavel Labath5eb721e2015-05-07 08:30:31 +00003778Error
3779NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003780{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003781 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3782
3783 if (log)
3784 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3785 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3786
Pavel Labathc0765592015-05-06 10:46:34 +00003787 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003788 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3789 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003790
3791 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003792 auto& context = thread_sp->GetThreadContext();
3793 const auto stop_was_requested = context.stop_requested;
3794 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003795
3796 // If we have a pending notification, remove this from the set.
3797 if (m_pending_notification_up)
3798 {
3799 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003800 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003801 }
3802
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003803 Error error;
3804 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003805 {
3806 // We can end up here if stop was initiated by LLGS but by this time a
3807 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003808 if (log)
3809 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003810 error = context.request_resume_function (tid, true);
3811 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003812 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003813 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3814 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003815 }
3816 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003817 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003818}
3819
3820void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003821NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003822{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003823 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3824 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003825 {
3826 // Yikes - we've already got a pending signal notification in progress.
3827 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003828 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 +00003829 __FUNCTION__,
3830 m_pending_notification_up->triggering_tid,
3831 notification_up->triggering_tid);
3832 }
3833 m_pending_notification_up = std::move(notification_up);
3834
Pavel Labath108c3252015-05-12 09:03:18 +00003835 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003836
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003837 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003838}
3839
3840void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003841NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003842{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003843 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3844
3845 if (log)
3846 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3847
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003848 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3849 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003850
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003851 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003852 {
3853 // We will need to wait for this new thread to stop as well before firing the
3854 // notification.
3855 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003856 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003857 }
3858}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003859
3860Error
3861NativeProcessLinux::DoOperation(Operation* op)
3862{
3863 m_monitor_up->DoOperation(op);
3864 return op->GetError();
3865}
3866
3867// Wrapper for ptrace to catch errors and log calls.
3868// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
3869long
3870NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
3871{
3872 long int result;
3873
3874 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3875
3876 PtraceDisplayBytes(req, data, data_size);
3877
3878 error.Clear();
3879 errno = 0;
3880 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
3881 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3882 else
3883 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3884
3885 if (result == -1)
3886 error.SetErrorToErrno();
3887
3888 if (log)
3889 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, result);
3890
3891 PtraceDisplayBytes(req, data, data_size);
3892
3893 if (log && error.GetError() != 0)
3894 {
3895 const char* str;
3896 switch (error.GetError())
3897 {
3898 case ESRCH: str = "ESRCH"; break;
3899 case EINVAL: str = "EINVAL"; break;
3900 case EBUSY: str = "EBUSY"; break;
3901 case EPERM: str = "EPERM"; break;
3902 default: str = error.AsCString();
3903 }
3904 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3905 }
3906
3907 return result;
3908}