blob: 41d6b7674a050cd0b51cf4f0e66b44b36f496aa1 [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"
Pavel Labathf805e192015-07-07 10:08:41 +000043#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000045#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000046#include "Plugins/Process/Utility/LinuxSignals.h"
47#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
Pavel Labathc7512fd2015-06-26 10:14:12 +0000229 Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000230 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,
Pavel Labathc7512fd2015-06-26 10:14:12 +0000235 size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +0000236 {
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 remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000241 long data;
242
243 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
244 if (log)
245 ProcessPOSIXLog::IncNestLevel();
246 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
247 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
248 pid, word_size, (void*)vm_addr, buf, size);
249
250 assert(sizeof(data) >= word_size);
251 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
252 {
Pavel Labath4a9babb2015-06-30 17:04:49 +0000253 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, &data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000254 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000255 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000256 if (log)
257 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000258 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000259 }
260
261 remainder = size - bytes_read;
262 remainder = remainder > word_size ? word_size : remainder;
263
264 // Copy the data into our buffer
265 for (unsigned i = 0; i < remainder; ++i)
266 dst[i] = ((data >> i*8) & 0xFF);
267
268 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
269 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
270 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
271 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
272 {
273 uintptr_t print_dst = 0;
274 // Format bytes from data by moving into print_dst for log output
275 for (unsigned i = 0; i < remainder; ++i)
276 print_dst |= (((data >> i*8) & 0xFF) << i*8);
277 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
278 (void*)vm_addr, print_dst, (unsigned long)data);
279 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000280 vm_addr += word_size;
281 dst += word_size;
282 }
283
284 if (log)
285 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000286 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +0000287 }
288
Pavel Labathc7512fd2015-06-26 10:14:12 +0000289 Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 DoWriteMemory(
291 lldb::pid_t pid,
292 lldb::addr_t vm_addr,
293 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000294 size_t size,
Pavel Labathc7512fd2015-06-26 10:14:12 +0000295 size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +0000296 {
297 // ptrace word size is determined by the host, not the child
298 static const unsigned word_size = sizeof(void*);
299 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000300 size_t remainder;
Pavel Labathc7512fd2015-06-26 10:14:12 +0000301 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000302
303 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
304 if (log)
305 ProcessPOSIXLog::IncNestLevel();
306 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
307 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
308 pid, word_size, (void*)vm_addr, buf, size);
309
310 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
311 {
312 remainder = size - bytes_written;
313 remainder = remainder > word_size ? word_size : remainder;
314
315 if (remainder == word_size)
316 {
317 unsigned long data = 0;
318 assert(sizeof(data) >= word_size);
319 for (unsigned i = 0; i < word_size; ++i)
320 data |= (unsigned long)src[i] << i*8;
321
322 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
323 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
324 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
325 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
326 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000327 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000328
Pavel Labath4a9babb2015-06-30 17:04:49 +0000329 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data);
330 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000332 if (log)
333 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000334 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000335 }
336 }
337 else
338 {
339 unsigned char buff[8];
Pavel Labathc7512fd2015-06-26 10:14:12 +0000340 size_t bytes_read;
341 error = DoReadMemory(pid, vm_addr, buff, word_size, bytes_read);
342 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000343 {
344 if (log)
345 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000346 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000347 }
348
349 memcpy(buff, src, remainder);
350
Pavel Labathc7512fd2015-06-26 10:14:12 +0000351 size_t bytes_written_rec;
352 error = DoWriteMemory(pid, vm_addr, buff, word_size, bytes_written_rec);
353 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000354 {
355 if (log)
356 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000357 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000358 }
359
360 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
361 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
362 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
363 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
364 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000365 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000366 }
367
368 vm_addr += word_size;
369 src += word_size;
370 }
371 if (log)
372 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000373 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000374 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000375} // end of anonymous namespace
376
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000377// Simple helper function to ensure flags are enabled on the given file
378// descriptor.
379static Error
380EnsureFDFlags(int fd, int flags)
381{
382 Error error;
383
384 int status = fcntl(fd, F_GETFL);
385 if (status == -1)
386 {
387 error.SetErrorToErrno();
388 return error;
389 }
390
391 if (fcntl(fd, F_SETFL, status | flags) == -1)
392 {
393 error.SetErrorToErrno();
394 return error;
395 }
396
397 return error;
398}
399
400// This class encapsulates the privileged thread which performs all ptrace and wait operations on
401// the inferior. The thread consists of a main loop which waits for events and processes them
402// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
403// the inferior process. Upon receiving this signal we do a waitpid to get more information
404// and dispatch to NativeProcessLinux::MonitorCallback.
405// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
406// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
407// pipe, and the completion of the operation is signalled over the semaphore.
408// - thread exit event: this is signaled from the Monitor destructor by closing the write end
409// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000410class NativeProcessLinux::Monitor
411{
Pavel Labath1107b5a2015-04-17 14:07:49 +0000412private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000413 // The initial monitor operation (launch or attach). It returns a inferior process id.
414 std::unique_ptr<InitialOperation> m_initial_operation_up;
415
416 ::pid_t m_child_pid = -1;
417 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000418
419 enum { READ, WRITE };
420 int m_pipefd[2] = {-1, -1};
421 int m_signal_fd = -1;
422 HostThread m_thread;
423
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000424 // current operation which must be executed on the priviliged thread
Pavel Labathc7512fd2015-06-26 10:14:12 +0000425 Mutex m_operation_mutex;
426 const Operation *m_operation = nullptr;
427 sem_t m_operation_sem;
428 Error m_operation_error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000429
Pavel Labath45f5cb32015-05-05 15:05:50 +0000430 unsigned m_operation_nesting_level = 0;
431
432 static constexpr char operation_command = 'o';
433 static constexpr char begin_block_command = '{';
434 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000435
Pavel Labath1107b5a2015-04-17 14:07:49 +0000436 void
437 HandleSignals();
438
439 void
440 HandleWait();
441
442 // Returns true if the thread should exit.
443 bool
444 HandleCommands();
445
446 void
447 MainLoop();
448
449 static void *
450 RunMonitor(void *arg);
451
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000452 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000453 WaitForAck();
454
455 void
456 BeginOperationBlock()
457 {
458 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
459 WaitForAck();
460 }
461
462 void
463 EndOperationBlock()
464 {
465 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
466 WaitForAck();
467 }
468
Pavel Labath1107b5a2015-04-17 14:07:49 +0000469public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000470 Monitor(const InitialOperation &initial_operation,
471 NativeProcessLinux *native_process)
472 : m_initial_operation_up(new InitialOperation(initial_operation)),
473 m_native_process(native_process)
474 {
475 sem_init(&m_operation_sem, 0, 0);
476 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000477
478 ~Monitor();
479
480 Error
481 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000482
483 void
Pavel Labath45f5cb32015-05-05 15:05:50 +0000484 Terminate();
485
Pavel Labathc7512fd2015-06-26 10:14:12 +0000486 Error
487 DoOperation(const Operation &op);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000488
489 class ScopedOperationLock {
490 Monitor &m_monitor;
491
492 public:
493 ScopedOperationLock(Monitor &monitor)
494 : m_monitor(monitor)
495 { m_monitor.BeginOperationBlock(); }
496
497 ~ScopedOperationLock()
498 { m_monitor.EndOperationBlock(); }
499 };
Pavel Labath1107b5a2015-04-17 14:07:49 +0000500};
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000501constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +0000502constexpr char NativeProcessLinux::Monitor::begin_block_command;
503constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000504
505Error
506NativeProcessLinux::Monitor::Initialize()
507{
508 Error error;
509
510 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
511 // listening for these signals over a signalfd file descriptors. This allows us to wait for
512 // multiple kinds of events with select.
513 sigset_t signals;
514 sigemptyset(&signals);
515 sigaddset(&signals, SIGCHLD);
516 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
517 if (m_signal_fd < 0)
518 {
519 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
520 __FUNCTION__, strerror(errno));
521
522 }
523
524 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
525 {
526 error.SetErrorToErrno();
527 return error;
528 }
529
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000530 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
531 return error;
532 }
533
534 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
535 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000536 if (!m_thread.IsJoinable())
537 return Error("Failed to create monitor thread for NativeProcessLinux.");
538
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000539 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000540 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000541}
542
Pavel Labathc7512fd2015-06-26 10:14:12 +0000543Error
544NativeProcessLinux::Monitor::DoOperation(const Operation &op)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000545{
546 if (m_thread.EqualsThread(pthread_self())) {
547 // If we're on the Monitor thread, we can simply execute the operation.
Pavel Labathc7512fd2015-06-26 10:14:12 +0000548 return op();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000549 }
550
551 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
552 Mutex::Locker lock(m_operation_mutex);
553
Pavel Labathc7512fd2015-06-26 10:14:12 +0000554 m_operation = &op;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000555
556 // notify the thread that an operation is ready to be processed
557 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
558
Pavel Labathc7512fd2015-06-26 10:14:12 +0000559 return WaitForAck();
Pavel Labath45f5cb32015-05-05 15:05:50 +0000560}
561
562void
563NativeProcessLinux::Monitor::Terminate()
564{
565 if (m_pipefd[WRITE] >= 0)
566 {
567 close(m_pipefd[WRITE]);
568 m_pipefd[WRITE] = -1;
569 }
570 if (m_thread.IsJoinable())
571 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +0000572}
573
Pavel Labath1107b5a2015-04-17 14:07:49 +0000574NativeProcessLinux::Monitor::~Monitor()
575{
Pavel Labath45f5cb32015-05-05 15:05:50 +0000576 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +0000577 if (m_pipefd[READ] >= 0)
578 close(m_pipefd[READ]);
579 if (m_signal_fd >= 0)
580 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000581 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000582}
583
584void
585NativeProcessLinux::Monitor::HandleSignals()
586{
587 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
588
589 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
590 // all the information from waitpid(). We just need to read all the signals so that we can
591 // sleep next time we reach select().
592 while (true)
593 {
594 signalfd_siginfo info;
595 ssize_t size = read(m_signal_fd, &info, sizeof info);
596 if (size == -1)
597 {
598 if (errno == EAGAIN || errno == EWOULDBLOCK)
599 break; // We are done.
600 if (errno == EINTR)
601 continue;
602 if (log)
603 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
604 __FUNCTION__, strerror(errno));
605 break;
606 }
607 if (size != sizeof info)
608 {
609 // We got incomplete information structure. This should not happen, let's just log
610 // that.
611 if (log)
612 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
613 "structure size is %zd, read returned %zd bytes",
614 __FUNCTION__, sizeof info, size);
615 break;
616 }
617 if (log)
618 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
619 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
620 }
621}
622
623void
624NativeProcessLinux::Monitor::HandleWait()
625{
626 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
627 // Process all pending waitpid notifications.
628 while (true)
629 {
630 int status = -1;
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000631 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000632
633 if (wait_pid == 0)
634 break; // We are done.
635
636 if (wait_pid == -1)
637 {
638 if (errno == EINTR)
639 continue;
640
641 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000642 log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
643 __FUNCTION__, strerror(errno));
Pavel Labath1107b5a2015-04-17 14:07:49 +0000644 break;
645 }
646
647 bool exited = false;
648 int signal = 0;
649 int exit_status = 0;
650 const char *status_cstr = NULL;
651 if (WIFSTOPPED(status))
652 {
653 signal = WSTOPSIG(status);
654 status_cstr = "STOPPED";
655 }
656 else if (WIFEXITED(status))
657 {
658 exit_status = WEXITSTATUS(status);
659 status_cstr = "EXITED";
660 exited = true;
661 }
662 else if (WIFSIGNALED(status))
663 {
664 signal = WTERMSIG(status);
665 status_cstr = "SIGNALED";
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000666 if (wait_pid == m_child_pid) {
Pavel Labath1107b5a2015-04-17 14:07:49 +0000667 exited = true;
668 exit_status = -1;
669 }
670 }
671 else
672 status_cstr = "(\?\?\?)";
673
674 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000675 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
Pavel Labath1107b5a2015-04-17 14:07:49 +0000676 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000677 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000678
679 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
680 }
681}
682
683bool
684NativeProcessLinux::Monitor::HandleCommands()
685{
686 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
687
688 while (true)
689 {
690 char command = 0;
691 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
692 if (size == -1)
693 {
694 if (errno == EAGAIN || errno == EWOULDBLOCK)
695 return false;
696 if (errno == EINTR)
697 continue;
698 if (log)
699 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
700 return true;
701 }
702 if (size == 0) // end of file - write end closed
703 {
704 if (log)
705 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000706 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000707 return true; // We are done.
708 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000709
710 switch (command)
711 {
712 case operation_command:
Pavel Labathc7512fd2015-06-26 10:14:12 +0000713 m_operation_error = (*m_operation)();
Pavel Labath45f5cb32015-05-05 15:05:50 +0000714 break;
715 case begin_block_command:
716 ++m_operation_nesting_level;
717 break;
718 case end_block_command:
719 assert(m_operation_nesting_level > 0);
720 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000721 break;
722 default:
723 if (log)
724 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
725 __FUNCTION__, command);
726 }
Pavel Labath45f5cb32015-05-05 15:05:50 +0000727
728 // notify calling thread that the command has been processed
729 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000730 }
731}
732
733void
734NativeProcessLinux::Monitor::MainLoop()
735{
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000736 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
737 m_initial_operation_up.reset();
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000738 m_child_pid = child_pid;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000739 sem_post(&m_operation_sem);
740
Pavel Labath1107b5a2015-04-17 14:07:49 +0000741 while (true)
742 {
743 fd_set fds;
744 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000745 // Only process waitpid events if we are outside of an operation block. Any pending
746 // events will be processed after we leave the block.
747 if (m_operation_nesting_level == 0)
748 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000749 FD_SET(m_pipefd[READ], &fds);
750
751 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
752 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
753 if (r < 0)
754 {
755 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
756 if (log)
757 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
758 __FUNCTION__, strerror(errno));
759 return;
760 }
761
762 if (FD_ISSET(m_pipefd[READ], &fds))
763 {
764 if (HandleCommands())
765 return;
766 }
767
768 if (FD_ISSET(m_signal_fd, &fds))
769 {
770 HandleSignals();
771 HandleWait();
772 }
773 }
774}
775
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000776Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000777NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000778{
779 Error error;
780 while (sem_wait(&m_operation_sem) != 0)
781 {
782 if (errno == EINTR)
783 continue;
784
785 error.SetErrorToErrno();
786 return error;
787 }
788
789 return m_operation_error;
790}
791
Pavel Labath1107b5a2015-04-17 14:07:49 +0000792void *
793NativeProcessLinux::Monitor::RunMonitor(void *arg)
794{
795 static_cast<Monitor *>(arg)->MainLoop();
796 return nullptr;
797}
798
799
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000800NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000801 char const **argv,
802 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000803 const FileSpec &stdin_file_spec,
804 const FileSpec &stdout_file_spec,
805 const FileSpec &stderr_file_spec,
806 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000807 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000808 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000809 m_argv(argv),
810 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000811 m_stdin_file_spec(stdin_file_spec),
812 m_stdout_file_spec(stdout_file_spec),
813 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000814 m_working_dir(working_dir),
815 m_launch_info(launch_info)
816{
817}
Todd Fialaaf245d12014-06-30 21:05:18 +0000818
819NativeProcessLinux::LaunchArgs::~LaunchArgs()
820{ }
821
Todd Fialaaf245d12014-06-30 21:05:18 +0000822// -----------------------------------------------------------------------------
823// Public Static Methods
824// -----------------------------------------------------------------------------
825
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000826Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000827NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000828 Module *exe_module,
829 ProcessLaunchInfo &launch_info,
830 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000831 NativeProcessProtocolSP &native_process_sp)
832{
833 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
834
835 Error error;
836
837 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000838 FileSpec working_dir{launch_info.GetWorkingDirectory()};
839 if (working_dir &&
840 (!working_dir.ResolvePath() ||
841 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000842 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000843 error.SetErrorStringWithFormat ("No such file or directory: %s",
844 working_dir.GetCString());
845 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000846 }
847
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000848 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000849
Chaoren Lind3173f32015-05-29 19:52:29 +0000850 // Default of empty will mean to use existing open file descriptors.
851 FileSpec stdin_file_spec{};
852 FileSpec stdout_file_spec{};
853 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000854
855 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000856 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000857 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000858
859 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000860 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000861 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000862
863 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000864 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000865 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000866
867 if (log)
868 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000869 if (stdin_file_spec)
870 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
871 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000872 else
873 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
874
Chaoren Lind3173f32015-05-29 19:52:29 +0000875 if (stdout_file_spec)
876 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
877 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000878 else
879 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
880
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 if (stderr_file_spec)
882 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
883 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000884 else
885 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
886 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000887
888 // Create the NativeProcessLinux in launch mode.
889 native_process_sp.reset (new NativeProcessLinux ());
890
891 if (log)
892 {
893 int i = 0;
894 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
895 {
896 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
897 ++i;
898 }
899 }
900
901 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
902 {
903 native_process_sp.reset ();
904 error.SetErrorStringWithFormat ("failed to register the native delegate");
905 return error;
906 }
907
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000908 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +0000909 exe_module,
910 launch_info.GetArguments ().GetConstArgumentVector (),
911 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000912 stdin_file_spec,
913 stdout_file_spec,
914 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000915 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000916 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000917 error);
918
919 if (error.Fail ())
920 {
921 native_process_sp.reset ();
922 if (log)
923 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
924 return error;
925 }
926
927 launch_info.SetProcessID (native_process_sp->GetID ());
928
929 return error;
930}
931
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000932Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000933NativeProcessLinux::AttachToProcess (
934 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000935 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000936 NativeProcessProtocolSP &native_process_sp)
937{
938 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
939 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
940 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
941
942 // Grab the current platform architecture. This should be Linux,
943 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000944 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000945 if (!platform_sp)
946 return Error("failed to get a valid default platform");
947
948 // Retrieve the architecture for the running process.
949 ArchSpec process_arch;
950 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
951 if (!error.Success ())
952 return error;
953
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000954 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000955
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000956 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000957 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000958 error.SetErrorStringWithFormat ("failed to register the native delegate");
959 return error;
960 }
961
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000962 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000964 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000965
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000966 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000967 return error;
968}
969
970// -----------------------------------------------------------------------------
971// Public Instance Methods
972// -----------------------------------------------------------------------------
973
974NativeProcessLinux::NativeProcessLinux () :
975 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
976 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000977 m_supports_mem_region (eLazyBoolCalculate),
978 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +0000979 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000980{
981}
982
983//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000984// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
985// Refer to Monitor and Operation classes to see why this is necessary.
986//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000987void
988NativeProcessLinux::LaunchInferior (
989 Module *module,
990 const char *argv[],
991 const char *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,
997 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000998{
999 if (module)
1000 m_arch = module->GetArchitecture ();
1001
Chaoren Linfa03ad22015-02-03 01:50:42 +00001002 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001003
1004 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +00001005 new LaunchArgs(module, argv, envp,
1006 stdin_file_spec,
1007 stdout_file_spec,
1008 stderr_file_spec,
1009 working_dir,
1010 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001011
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001012 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001013 if (!error.Success ())
1014 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001015}
1016
1017void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001018NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001019{
1020 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1021 if (log)
1022 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1023
1024 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001025 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001026 if (!platform_sp)
1027 {
1028 if (log)
1029 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1030 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001031 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 }
1033
1034 // Gather info about the process.
1035 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001036 if (!platform_sp->GetProcessInfo (pid, process_info))
1037 {
1038 if (log)
1039 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1040 error.SetErrorString ("failed to get process info");
1041 return;
1042 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
1044 // Resolve the executable module
1045 ModuleSP exe_module_sp;
1046 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001047 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001048 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001049 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001050 if (!error.Success())
1051 return;
1052
1053 // Set the architecture to the exe architecture.
1054 m_arch = exe_module_sp->GetArchitecture();
1055 if (log)
1056 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1057
1058 m_pid = pid;
1059 SetState(eStateAttaching);
1060
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001061 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001062 if (!error.Success ())
1063 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001064}
1065
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001066void
1067NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001068{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001069 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001070}
1071
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001072::pid_t
1073NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001074{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001075 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001076
1077 const char **argv = args->m_argv;
1078 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +00001079 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +00001080
1081 lldb_utility::PseudoTerminal terminal;
1082 const size_t err_len = 1024;
1083 char err_str[err_len];
1084 lldb::pid_t pid;
1085 NativeThreadProtocolSP thread_sp;
1086
1087 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001088
1089 // Propagate the environment if one is not supplied.
1090 if (envp == NULL || envp[0] == NULL)
1091 envp = const_cast<const char **>(environ);
1092
1093 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1094 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001095 error.SetErrorToGenericError();
1096 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1097 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001098 }
1099
1100 // Recognized child exit status codes.
1101 enum {
1102 ePtraceFailed = 1,
1103 eDupStdinFailed,
1104 eDupStdoutFailed,
1105 eDupStderrFailed,
1106 eChdirFailed,
1107 eExecFailed,
1108 eSetGidFailed
1109 };
1110
1111 // Child process.
1112 if (pid == 0)
1113 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001114 // FIXME consider opening a pipe between parent/child and have this forked child
1115 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001116
Todd Fiala75f47c32014-10-11 21:42:09 +00001117 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001118 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001119 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001120 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001121
Pavel Labath493c3a12015-02-04 10:36:57 +00001122 // terminal has already dupped the tty descriptors to stdin/out/err.
1123 // This closes original fd from which they were copied (and avoids
1124 // leaking descriptors to the debugged process.
1125 terminal.CloseSlaveFileDescriptor();
1126
Todd Fialaaf245d12014-06-30 21:05:18 +00001127 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001128 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001129 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001130
1131 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001132 if (setpgid(0, 0) != 0)
1133 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001134 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001135 // Don't allow this to prevent an inferior exec.
1136 }
1137
1138 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +00001139 if (args->m_stdin_file_spec)
1140 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001141 exit(eDupStdinFailed);
1142
Chaoren Lind3173f32015-05-29 19:52:29 +00001143 if (args->m_stdout_file_spec)
1144 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001145 exit(eDupStdoutFailed);
1146
Chaoren Lind3173f32015-05-29 19:52:29 +00001147 if (args->m_stderr_file_spec)
1148 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001149 exit(eDupStderrFailed);
1150
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001151 // Close everything besides stdin, stdout, and stderr that has no file
1152 // action to avoid leaking
1153 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1154 if (!args->m_launch_info.GetFileActionForFD(fd))
1155 close(fd);
1156
Todd Fialaaf245d12014-06-30 21:05:18 +00001157 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +00001158 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +00001159 exit(eChdirFailed);
1160
Todd Fiala0bce1b62014-08-17 00:10:50 +00001161 // Disable ASLR if requested.
1162 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1163 {
1164 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1165 if (old_personality == -1)
1166 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001167 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001168 }
1169 else
1170 {
1171 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1172 if (new_personality == -1)
1173 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001174 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001175 }
1176 else
1177 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001178 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001179 }
1180 }
1181 }
1182
Todd Fiala75f47c32014-10-11 21:42:09 +00001183 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001184 execve(argv[0],
1185 const_cast<char *const *>(argv),
1186 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001187
1188 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001189 exit(eExecFailed);
1190 }
1191
Todd Fiala75f47c32014-10-11 21:42:09 +00001192 //
1193 // This is the parent code here.
1194 //
1195 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1196
Todd Fialaaf245d12014-06-30 21:05:18 +00001197 // Wait for the child process to trap on its call to execve.
1198 ::pid_t wpid;
1199 int status;
1200 if ((wpid = waitpid(pid, &status, 0)) < 0)
1201 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001202 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001203 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001204 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1205 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001206
1207 // Mark the inferior as invalid.
1208 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001209 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001210
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001211 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001212 }
1213 else if (WIFEXITED(status))
1214 {
1215 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001216 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001217 switch (WEXITSTATUS(status))
1218 {
1219 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001220 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001221 break;
1222 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001223 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001224 break;
1225 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001226 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001227 break;
1228 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001229 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001230 break;
1231 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001232 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001233 break;
1234 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001235 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001236 break;
1237 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001238 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001239 break;
1240 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001241 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001242 break;
1243 }
1244
1245 if (log)
1246 {
1247 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1248 __FUNCTION__,
1249 WEXITSTATUS(status));
1250 }
1251
1252 // Mark the inferior as invalid.
1253 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001254 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001255
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001256 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001257 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001258 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 "Could not sync with inferior process.");
1260
1261 if (log)
1262 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1263
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001264 error = SetDefaultPtraceOpts(pid);
1265 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001266 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001267 if (log)
1268 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001269 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001270
1271 // Mark the inferior as invalid.
1272 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001273 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001274
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001275 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001276 }
1277
1278 // Release the master terminal descriptor and pass it off to the
1279 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001280 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1281 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001282
1283 // Set the terminal fd to be in non blocking mode (it simplifies the
1284 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1285 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001286 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1287 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001288 {
1289 if (log)
1290 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001291 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001292
1293 // Mark the inferior as invalid.
1294 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001295 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001296
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001297 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001298 }
1299
1300 if (log)
1301 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1302
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001303 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001304 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001305 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001306 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001307
1308 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001309 SetCurrentThreadID (thread_sp->GetID ());
1310 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001311
Todd Fialaaf245d12014-06-30 21:05:18 +00001312 if (log)
1313 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001314 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001315 {
1316 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1317 }
1318 else
1319 {
1320 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001321 __FUNCTION__, error.AsCString ());
1322 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001323 }
1324 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001325 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001326}
1327
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001328::pid_t
1329NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001330{
Todd Fialaaf245d12014-06-30 21:05:18 +00001331 lldb::ThreadSP inferior;
1332 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1333
1334 // Use a map to keep track of the threads which we have attached/need to attach.
1335 Host::TidMap tids_to_attach;
1336 if (pid <= 1)
1337 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001338 error.SetErrorToGenericError();
1339 error.SetErrorString("Attaching to process 1 is not allowed.");
1340 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001341 }
1342
1343 while (Host::FindProcessThreads(pid, tids_to_attach))
1344 {
1345 for (Host::TidMap::iterator it = tids_to_attach.begin();
1346 it != tids_to_attach.end();)
1347 {
1348 if (it->second == false)
1349 {
1350 lldb::tid_t tid = it->first;
1351
1352 // Attach to the requested process.
1353 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001354 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001355 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001356 {
1357 // No such thread. The thread may have exited.
1358 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001359 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001360 {
1361 it = tids_to_attach.erase(it);
1362 continue;
1363 }
1364 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001365 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001366 }
1367
1368 int status;
1369 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1370 // At this point we should have a thread stopped if waitpid succeeds.
1371 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1372 {
1373 // No such thread. The thread may have exited.
1374 // More error handling may be needed.
1375 if (errno == ESRCH)
1376 {
1377 it = tids_to_attach.erase(it);
1378 continue;
1379 }
1380 else
1381 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001382 error.SetErrorToErrno();
1383 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001384 }
1385 }
1386
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001387 error = SetDefaultPtraceOpts(tid);
1388 if (error.Fail())
1389 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001390
1391 if (log)
1392 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1393
1394 it->second = true;
1395
1396 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001397 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001398 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001399
1400 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001401 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001402 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001403 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001404 }
1405
1406 // move the loop forward
1407 ++it;
1408 }
1409 }
1410
1411 if (tids_to_attach.size() > 0)
1412 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001413 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001414 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001415 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001416 }
1417 else
1418 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001419 error.SetErrorToGenericError();
1420 error.SetErrorString("No such process.");
1421 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001422 }
1423
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001424 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001425}
1426
Chaoren Lin97ccc292015-02-03 01:51:12 +00001427Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001428NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1429{
1430 long ptrace_opts = 0;
1431
1432 // Have the child raise an event on exit. This is used to keep the child in
1433 // limbo until it is destroyed.
1434 ptrace_opts |= PTRACE_O_TRACEEXIT;
1435
1436 // Have the tracer trace threads which spawn in the inferior process.
1437 // TODO: if we want to support tracing the inferiors' child, add the
1438 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1439 ptrace_opts |= PTRACE_O_TRACECLONE;
1440
1441 // Have the tracer notify us before execve returns
1442 // (needed to disable legacy SIGTRAP generation)
1443 ptrace_opts |= PTRACE_O_TRACEEXEC;
1444
Pavel Labath4a9babb2015-06-30 17:04:49 +00001445 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +00001446}
1447
1448static ExitType convert_pid_status_to_exit_type (int status)
1449{
1450 if (WIFEXITED (status))
1451 return ExitType::eExitTypeExit;
1452 else if (WIFSIGNALED (status))
1453 return ExitType::eExitTypeSignal;
1454 else if (WIFSTOPPED (status))
1455 return ExitType::eExitTypeStop;
1456 else
1457 {
1458 // We don't know what this is.
1459 return ExitType::eExitTypeInvalid;
1460 }
1461}
1462
1463static int convert_pid_status_to_return_code (int status)
1464{
1465 if (WIFEXITED (status))
1466 return WEXITSTATUS (status);
1467 else if (WIFSIGNALED (status))
1468 return WTERMSIG (status);
1469 else if (WIFSTOPPED (status))
1470 return WSTOPSIG (status);
1471 else
1472 {
1473 // We don't know what this is.
1474 return ExitType::eExitTypeInvalid;
1475 }
1476}
1477
Pavel Labath1107b5a2015-04-17 14:07:49 +00001478// Handles all waitpid events from the inferior process.
1479void
1480NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001481 bool exited,
1482 int signal,
1483 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001484{
1485 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1486
Todd Fialaaf245d12014-06-30 21:05:18 +00001487 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001488 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001489
1490 // Handle when the thread exits.
1491 if (exited)
1492 {
1493 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001494 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 +00001495
1496 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001497 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001498
1499 if (is_main_thread)
1500 {
1501 // We only set the exit status and notify the delegate if we haven't already set the process
1502 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1503 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001504 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001505 if (!already_notified)
1506 {
1507 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001508 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 +00001509 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001510 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001511
1512 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001513 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001514 }
1515 else
1516 {
1517 if (log)
1518 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1519 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001520 }
1521 else
1522 {
1523 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1524 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1525 // and we would have done an all-stop then.
1526 if (log)
1527 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 +00001528 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001529 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001530 }
1531
1532 // Get details on the signal raised.
1533 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001534 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001535 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001536 {
1537 // We have retrieved the signal info. Dispatch appropriately.
1538 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001539 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001540 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001541 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001542 }
1543 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001544 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001545 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001546 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001547 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001548 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1549 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1550 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1551 // generally not needed (one use case is debugging background task being managed by a
1552 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1553 // stop which happens before the group stop. This done by MonitorSignal and works
1554 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001555 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001556 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);
1557 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001558 }
1559 else
1560 {
1561 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1562
1563 // A return value of ESRCH means the thread/process is no longer on the system,
1564 // so it was killed somehow outside of our control. Either way, we can't do anything
1565 // with it anymore.
1566
Todd Fialaaf245d12014-06-30 21:05:18 +00001567 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001568 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001569
1570 if (log)
1571 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001572 __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 +00001573
1574 if (is_main_thread)
1575 {
1576 // Notify the delegate - our process is not available but appears to have been killed outside
1577 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001578 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1579 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001580 }
1581 else
1582 {
1583 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1584 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001585 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 +00001586 }
1587 }
1588 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001589}
1590
1591void
Pavel Labath426bdf82015-04-28 07:51:52 +00001592NativeProcessLinux::WaitForNewThread(::pid_t tid)
1593{
1594 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1595
1596 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1597
1598 if (new_thread_sp)
1599 {
1600 // We are already tracking the thread - we got the event on the new thread (see
1601 // MonitorSignal) before this one. We are done.
1602 return;
1603 }
1604
1605 // The thread is not tracked yet, let's wait for it to appear.
1606 int status = -1;
1607 ::pid_t wait_pid;
1608 do
1609 {
1610 if (log)
1611 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1612 wait_pid = waitpid(tid, &status, __WALL);
1613 }
1614 while (wait_pid == -1 && errno == EINTR);
1615 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1616 // some checks just in case.
1617 if (wait_pid != tid) {
1618 if (log)
1619 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1620 // The only way I know of this could happen is if the whole process was
1621 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1622 return;
1623 }
1624 if (WIFEXITED(status))
1625 {
1626 if (log)
1627 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1628 // Also a very improbable event.
1629 return;
1630 }
1631
1632 siginfo_t info;
1633 Error error = GetSignalInfo(tid, &info);
1634 if (error.Fail())
1635 {
1636 if (log)
1637 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1638 return;
1639 }
1640
1641 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1642 {
1643 // We should be getting a thread creation signal here, but we received something
1644 // else. There isn't much we can do about it now, so we will just log that. Since the
1645 // thread is alive and we are receiving events from it, we shall pretend that it was
1646 // created properly.
1647 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);
1648 }
1649
1650 if (log)
1651 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1652 __FUNCTION__, GetID (), tid);
1653
1654 new_thread_sp = AddThread(tid);
1655 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1656 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001657 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001658}
1659
1660void
Todd Fialaaf245d12014-06-30 21:05:18 +00001661NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1662{
1663 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1664 const bool is_main_thread = (pid == GetID ());
1665
1666 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1667 if (!info)
1668 return;
1669
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001670 Mutex::Locker locker (m_threads_mutex);
1671
Todd Fialaaf245d12014-06-30 21:05:18 +00001672 // See if we can find a thread for this signal.
1673 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1674 if (!thread_sp)
1675 {
1676 if (log)
1677 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1678 }
1679
1680 switch (info->si_code)
1681 {
1682 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1683 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1684 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1685
1686 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1687 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001688 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001689 // creation.
1690 // We don't want to do anything with the parent thread so we just resume it. In case we
1691 // want to implement "break on thread creation" functionality, we would need to stop
1692 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001693
Pavel Labath426bdf82015-04-28 07:51:52 +00001694 unsigned long event_message = 0;
1695 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001696 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001697 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001698 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 +00001699 } else
1700 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001701
Pavel Labath5fd24c62015-04-23 09:04:35 +00001702 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001703 break;
1704 }
1705
1706 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001707 {
1708 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001709 if (log)
1710 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001711
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001712 // Exec clears any pending notifications.
1713 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001714
1715 // 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 +00001716 if (log)
1717 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1718
1719 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001720 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001721 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1722 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001723 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001724 main_thread_sp = thread_sp;
1725 if (log)
1726 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001727 }
1728 else
1729 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001730 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001731 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001732 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001733 }
1734 }
1735
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001736 m_threads.clear ();
1737
1738 if (main_thread_sp)
1739 {
1740 m_threads.push_back (main_thread_sp);
1741 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001742 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001743 }
1744 else
1745 {
1746 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1747 if (log)
1748 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1749 }
1750
Chaoren Linfa03ad22015-02-03 01:50:42 +00001751 // Tell coordinator about about the "new" (since exec) stopped main thread.
1752 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001753 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001754
1755 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1756 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001757 // Let our delegate know we have just exec'd.
1758 NotifyDidExec ();
1759
1760 // If we have a main thread, indicate we are stopped.
1761 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001762
1763 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001764 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001765
Todd Fialaaf245d12014-06-30 21:05:18 +00001766 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001767 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001768
1769 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1770 {
1771 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001772 // We don't want to do anything with the thread so we just resume it. In case we
1773 // want to implement "break on thread exit" functionality, we would need to stop
1774 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001775
Todd Fialaaf245d12014-06-30 21:05:18 +00001776 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001777 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001778 data = -1;
1779
1780 if (log)
1781 {
1782 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1783 __FUNCTION__,
1784 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1785 pid,
1786 is_main_thread ? "is main thread" : "not main thread");
1787 }
1788
Todd Fialaaf245d12014-06-30 21:05:18 +00001789 if (is_main_thread)
1790 {
1791 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001792 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001793
Pavel Labath6e351632015-05-15 13:30:59 +00001794 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001795
1796 break;
1797 }
1798
1799 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001800 case TRAP_TRACE: // We receive this on single stepping.
1801 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001802 if (thread_sp)
1803 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001804 // If a watchpoint was hit, report it
1805 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001806 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001807 if (error.Fail() && log)
1808 log->Printf("NativeProcessLinux::%s() "
1809 "received error while checking for watchpoint hits, "
1810 "pid = %" PRIu64 " error = %s",
1811 __FUNCTION__, pid, error.AsCString());
1812 if (wp_index != LLDB_INVALID_INDEX32)
1813 {
1814 MonitorWatchpoint(pid, thread_sp, wp_index);
1815 break;
1816 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001817 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001818 // Otherwise, report step over
1819 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001820 break;
1821
1822 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001823#if defined __mips__
1824 // For mips there is no special signal for watchpoint
1825 // So we check for watchpoint in kernel trap
1826 if (thread_sp)
1827 {
1828 // If a watchpoint was hit, report it
1829 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001830 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001831 if (error.Fail() && log)
1832 log->Printf("NativeProcessLinux::%s() "
1833 "received error while checking for watchpoint hits, "
1834 "pid = %" PRIu64 " error = %s",
1835 __FUNCTION__, pid, error.AsCString());
1836 if (wp_index != LLDB_INVALID_INDEX32)
1837 {
1838 MonitorWatchpoint(pid, thread_sp, wp_index);
1839 break;
1840 }
1841 }
1842 // NO BREAK
1843#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001844 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001845 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 break;
1847
1848 case SIGTRAP:
1849 case (SIGTRAP | 0x80):
1850 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001851 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1852
Todd Fialaaf245d12014-06-30 21:05:18 +00001853 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001854 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001855 break;
1856
1857 default:
1858 assert(false && "Unexpected SIGTRAP code!");
1859 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001860 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1861 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001862 break;
1863
1864 }
1865}
1866
1867void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001868NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1869{
1870 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1871 if (log)
1872 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1873 __FUNCTION__, pid);
1874
1875 if (thread_sp)
1876 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1877
1878 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001879 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001880
1881 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1882 // This would have already happened at the time the Resume() with step operation was signaled.
1883 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1884 // once all running threads have checked in as stopped.
1885 SetCurrentThreadID(pid);
1886 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001887 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001888}
1889
1890void
1891NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1892{
1893 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1894 if (log)
1895 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1896 __FUNCTION__, pid);
1897
1898 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001899 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001900
1901 // Mark the thread as stopped at breakpoint.
1902 if (thread_sp)
1903 {
1904 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1905 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1906 if (error.Fail())
1907 if (log)
1908 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1909 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001910
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001911 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001912 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001913 }
1914 else
1915 if (log)
1916 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1917 "warning, cannot process software breakpoint since no thread metadata",
1918 __FUNCTION__, pid);
1919
1920
1921 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001922 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001923}
1924
1925void
1926NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1927{
1928 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1929 if (log)
1930 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1931 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1932 __FUNCTION__, pid, wp_index);
1933
1934 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001935 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001936
1937 // Mark the thread as stopped at watchpoint.
1938 // The address is at (lldb::addr_t)info->si_addr if we need it.
1939 lldbassert(thread_sp && "thread_sp cannot be NULL");
1940 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1941
1942 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001943 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001944}
1945
1946void
Todd Fialaaf245d12014-06-30 21:05:18 +00001947NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1948{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001949 assert (info && "null info");
1950 if (!info)
1951 return;
1952
1953 const int signo = info->si_signo;
1954 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001955
1956 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1957
1958 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1959 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1960 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1961 //
1962 // IOW, user generated signals never generate what we consider to be a
1963 // "crash".
1964 //
1965 // Similarly, ACK signals generated by this monitor.
1966
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001967 Mutex::Locker locker (m_threads_mutex);
1968
Todd Fialaaf245d12014-06-30 21:05:18 +00001969 // See if we can find a thread for this signal.
1970 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1971 if (!thread_sp)
1972 {
1973 if (log)
1974 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1975 }
1976
1977 // Handle the signal.
1978 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1979 {
1980 if (log)
1981 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1982 __FUNCTION__,
1983 GetUnixSignals ().GetSignalAsCString (signo),
1984 signo,
1985 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1986 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001987 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001988 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001989 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001990
Todd Fiala58a2f662014-08-12 17:02:07 +00001991 // Check for new thread notification.
1992 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1993 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001994 // A new thread creation is being signaled. This is one of two parts that come in
1995 // a non-deterministic order. This code handles the case where the new thread event comes
1996 // before the event on the parent thread. For the opposite case see code in
1997 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00001998 if (log)
1999 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2000 __FUNCTION__, GetID (), pid);
2001
Pavel Labath5fd24c62015-04-23 09:04:35 +00002002 thread_sp = AddThread(pid);
2003 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2004 // We can now resume the newly created thread.
2005 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2006 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002007 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002008 // Done handling.
2009 return;
2010 }
2011
2012 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002013 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002014 {
2015 // This is a tgkill()-based stop.
2016 if (thread_sp)
2017 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002018 if (log)
2019 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2020 __FUNCTION__,
2021 GetID (),
2022 pid);
2023
Chaoren Linaab58632015-02-03 01:50:57 +00002024 // Check that we're not already marked with a stop reason.
2025 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2026 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2027 // and that, without an intervening resume, we received another stop. It is more likely
2028 // that we are missing the marking of a run state somewhere if we find that the thread was
2029 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002030 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2031 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002032
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002033 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002034 if (!StateIsStoppedState (thread_state, false))
2035 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002036 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2037 // Generally, these are not important stops and we don't want to report them as
2038 // they are just used to stop other threads when one thread (the one with the
2039 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2040 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2041 // leave the signal intact if this is the thread that was chosen as the
2042 // triggering thread.
2043 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002044 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002045 else
2046 linux_thread_sp->SetStoppedBySignal(0);
2047
Chaoren Linaab58632015-02-03 01:50:57 +00002048 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002049 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002050 }
2051 else
2052 {
2053 if (log)
2054 {
2055 // Retrieve the signal name if the thread was stopped by a signal.
2056 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002057 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002058 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2059 if (!signal_name)
2060 signal_name = "<no-signal-name>";
2061
2062 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",
2063 __FUNCTION__,
2064 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002065 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002066 StateAsCString (thread_state),
2067 stop_signo,
2068 signal_name);
2069 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002070 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002071 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002072 }
2073
2074 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002075 return;
2076 }
2077
2078 if (log)
2079 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2080
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002081 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002082 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002083
Pavel Labathc4e25c92015-05-29 10:13:03 +00002084 if (thread_sp)
2085 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002086
2087 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002088 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002089}
2090
Tamas Berghammere7708682015-04-22 10:00:23 +00002091namespace {
2092
2093struct EmulatorBaton
2094{
2095 NativeProcessLinux* m_process;
2096 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002097
Pavel Labath6648fcc2015-04-27 09:21:14 +00002098 // eRegisterKindDWARF -> RegsiterValue
2099 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2100
2101 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002102 m_process(process), m_reg_context(reg_context) {}
2103};
2104
2105} // anonymous namespace
2106
2107static size_t
2108ReadMemoryCallback (EmulateInstruction *instruction,
2109 void *baton,
2110 const EmulateInstruction::Context &context,
2111 lldb::addr_t addr,
2112 void *dst,
2113 size_t length)
2114{
2115 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2116
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002117 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002118 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2119 return bytes_read;
2120}
2121
2122static bool
2123ReadRegisterCallback (EmulateInstruction *instruction,
2124 void *baton,
2125 const RegisterInfo *reg_info,
2126 RegisterValue &reg_value)
2127{
2128 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2129
Pavel Labath6648fcc2015-04-27 09:21:14 +00002130 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2131 if (it != emulator_baton->m_register_values.end())
2132 {
2133 reg_value = it->second;
2134 return true;
2135 }
2136
Tamas Berghammere7708682015-04-22 10:00:23 +00002137 // The emulator only fill in the dwarf regsiter numbers (and in some case
2138 // the generic register numbers). Get the full register info from the
2139 // register context based on the dwarf register numbers.
2140 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2141 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2142
2143 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002144 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002145 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002146
Pavel Labath6648fcc2015-04-27 09:21:14 +00002147 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002148}
2149
2150static bool
2151WriteRegisterCallback (EmulateInstruction *instruction,
2152 void *baton,
2153 const EmulateInstruction::Context &context,
2154 const RegisterInfo *reg_info,
2155 const RegisterValue &reg_value)
2156{
2157 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002158 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002159 return true;
2160}
2161
2162static size_t
2163WriteMemoryCallback (EmulateInstruction *instruction,
2164 void *baton,
2165 const EmulateInstruction::Context &context,
2166 lldb::addr_t addr,
2167 const void *dst,
2168 size_t length)
2169{
2170 return length;
2171}
2172
2173static lldb::addr_t
2174ReadFlags (NativeRegisterContext* regsiter_context)
2175{
2176 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2177 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2178 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2179}
2180
2181Error
2182NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2183{
2184 Error error;
2185 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2186
2187 std::unique_ptr<EmulateInstruction> emulator_ap(
2188 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2189
2190 if (emulator_ap == nullptr)
2191 return Error("Instruction emulator not found!");
2192
2193 EmulatorBaton baton(this, register_context_sp.get());
2194 emulator_ap->SetBaton(&baton);
2195 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2196 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2197 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2198 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2199
2200 if (!emulator_ap->ReadInstruction())
2201 return Error("Read instruction failed!");
2202
Pavel Labath6648fcc2015-04-27 09:21:14 +00002203 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2204
2205 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2206 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2207
2208 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2209 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2210
Tamas Berghammere7708682015-04-22 10:00:23 +00002211 lldb::addr_t next_pc;
2212 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002213 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002214 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002215 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2216 next_pc = pc_it->second.GetAsUInt64();
2217
2218 if (flags_it != baton.m_register_values.end())
2219 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002220 else
2221 next_flags = ReadFlags (register_context_sp.get());
2222 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002223 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002224 {
2225 // Emulate instruction failed and it haven't changed PC. Advance PC
2226 // with the size of the current opcode because the emulation of all
2227 // PC modifying instruction should be successful. The failure most
2228 // likely caused by a not supported instruction which don't modify PC.
2229 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2230 next_flags = ReadFlags (register_context_sp.get());
2231 }
2232 else
2233 {
2234 // The instruction emulation failed after it modified the PC. It is an
2235 // unknown error where we can't continue because the next instruction is
2236 // modifying the PC but we don't know how.
2237 return Error ("Instruction emulation failed unexpectedly.");
2238 }
2239
2240 if (m_arch.GetMachine() == llvm::Triple::arm)
2241 {
2242 if (next_flags & 0x20)
2243 {
2244 // Thumb mode
2245 error = SetSoftwareBreakpoint(next_pc, 2);
2246 }
2247 else
2248 {
2249 // Arm mode
2250 error = SetSoftwareBreakpoint(next_pc, 4);
2251 }
2252 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002253 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002254 || m_arch.GetMachine() == llvm::Triple::mips64el
2255 || m_arch.GetMachine() == llvm::Triple::mips
2256 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002257 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002258 else
2259 {
2260 // No size hint is given for the next breakpoint
2261 error = SetSoftwareBreakpoint(next_pc, 0);
2262 }
2263
Tamas Berghammere7708682015-04-22 10:00:23 +00002264 if (error.Fail())
2265 return error;
2266
2267 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2268
2269 return Error();
2270}
2271
2272bool
2273NativeProcessLinux::SupportHardwareSingleStepping() const
2274{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002275 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002276 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
2277 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002278 return false;
2279 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002280}
2281
Todd Fialaaf245d12014-06-30 21:05:18 +00002282Error
2283NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2284{
Todd Fialaaf245d12014-06-30 21:05:18 +00002285 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2286 if (log)
2287 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2288
Tamas Berghammere7708682015-04-22 10:00:23 +00002289 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002290
Pavel Labath45f5cb32015-05-05 15:05:50 +00002291 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002292 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002293
Tamas Berghammere7708682015-04-22 10:00:23 +00002294 if (software_single_step)
2295 {
2296 for (auto thread_sp : m_threads)
2297 {
2298 assert (thread_sp && "thread list should not contain NULL threads");
2299
2300 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2301 if (action == nullptr)
2302 continue;
2303
2304 if (action->state == eStateStepping)
2305 {
2306 Error error = SetupSoftwareSingleStepping(thread_sp);
2307 if (error.Fail())
2308 return error;
2309 }
2310 }
2311 }
2312
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002313 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002314 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002315 assert (thread_sp && "thread list should not contain NULL threads");
2316
2317 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2318
2319 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002320 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002321 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002322 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2323 __FUNCTION__, GetID (), thread_sp->GetID ());
2324 continue;
2325 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002326
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002327 if (log)
2328 {
2329 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2330 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2331 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002332
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002333 switch (action->state)
2334 {
2335 case eStateRunning:
2336 {
2337 // Run the thread, possibly feeding it the signal.
2338 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002339 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002340 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2341 {
2342 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2343 // Pass this signal number on to the inferior to handle.
2344 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2345 if (resume_result.Success())
2346 SetState(eStateRunning, true);
2347 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002348 },
2349 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002350 break;
2351 }
2352
2353 case eStateStepping:
2354 {
2355 // Request the step.
2356 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002357 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002358 [=](lldb::tid_t tid_to_step, bool supress_signal)
2359 {
2360 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002361
Pavel Labathc0765592015-05-06 10:46:34 +00002362 Error step_result;
2363 if (software_single_step)
2364 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2365 else
2366 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002367
Pavel Labathc0765592015-05-06 10:46:34 +00002368 assert (step_result.Success() && "SingleStep() failed");
2369 if (step_result.Success())
2370 SetState(eStateStepping, true);
2371 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002372 },
2373 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002374 break;
2375 }
2376
2377 case eStateSuspended:
2378 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002379 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002380
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002381 default:
2382 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2383 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002384 }
2385 }
2386
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002387 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002388}
2389
2390Error
2391NativeProcessLinux::Halt ()
2392{
2393 Error error;
2394
Todd Fialaaf245d12014-06-30 21:05:18 +00002395 if (kill (GetID (), SIGSTOP) != 0)
2396 error.SetErrorToErrno ();
2397
2398 return error;
2399}
2400
2401Error
2402NativeProcessLinux::Detach ()
2403{
2404 Error error;
2405
2406 // Tell ptrace to detach from the process.
2407 if (GetID () != LLDB_INVALID_PROCESS_ID)
2408 error = Detach (GetID ());
2409
2410 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00002411 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002412
2413 // No error.
2414 return error;
2415}
2416
2417Error
2418NativeProcessLinux::Signal (int signo)
2419{
2420 Error error;
2421
2422 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2423 if (log)
2424 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2425 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2426
2427 if (kill(GetID(), signo))
2428 error.SetErrorToErrno();
2429
2430 return error;
2431}
2432
2433Error
Chaoren Line9547b82015-02-03 01:51:00 +00002434NativeProcessLinux::Interrupt ()
2435{
2436 // Pick a running thread (or if none, a not-dead stopped thread) as
2437 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002438 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2439
2440 NativeThreadProtocolSP running_thread_sp;
2441 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002442
2443 if (log)
2444 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2445
Pavel Labath45f5cb32015-05-05 15:05:50 +00002446 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002447 Mutex::Locker locker (m_threads_mutex);
2448
2449 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002450 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002451 // The thread shouldn't be null but lets just cover that here.
2452 if (!thread_sp)
2453 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002454
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002455 // If we have a running or stepping thread, we'll call that the
2456 // target of the interrupt.
2457 const auto thread_state = thread_sp->GetState ();
2458 if (thread_state == eStateRunning ||
2459 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002460 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002461 running_thread_sp = thread_sp;
2462 break;
2463 }
2464 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2465 {
2466 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2467 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002468 }
2469 }
2470
2471 if (!running_thread_sp && !stopped_thread_sp)
2472 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002473 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002474 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002475 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002476
Chaoren Line9547b82015-02-03 01:51:00 +00002477 return error;
2478 }
2479
2480 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2481
2482 if (log)
2483 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2484 __FUNCTION__,
2485 GetID (),
2486 running_thread_sp ? "running" : "stopped",
2487 deferred_signal_thread_sp->GetID ());
2488
Pavel Labathed89c7f2015-05-06 12:22:37 +00002489 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002490
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002491 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002492}
2493
2494Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002495NativeProcessLinux::Kill ()
2496{
2497 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2498 if (log)
2499 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2500
2501 Error error;
2502
2503 switch (m_state)
2504 {
2505 case StateType::eStateInvalid:
2506 case StateType::eStateExited:
2507 case StateType::eStateCrashed:
2508 case StateType::eStateDetached:
2509 case StateType::eStateUnloaded:
2510 // Nothing to do - the process is already dead.
2511 if (log)
2512 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2513 return error;
2514
2515 case StateType::eStateConnected:
2516 case StateType::eStateAttaching:
2517 case StateType::eStateLaunching:
2518 case StateType::eStateStopped:
2519 case StateType::eStateRunning:
2520 case StateType::eStateStepping:
2521 case StateType::eStateSuspended:
2522 // We can try to kill a process in these states.
2523 break;
2524 }
2525
2526 if (kill (GetID (), SIGKILL) != 0)
2527 {
2528 error.SetErrorToErrno ();
2529 return error;
2530 }
2531
2532 return error;
2533}
2534
2535static Error
2536ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2537{
2538 memory_region_info.Clear();
2539
2540 StringExtractor line_extractor (maps_line.c_str ());
2541
2542 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2543 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2544
2545 // Parse out the starting address
2546 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2547
2548 // Parse out hyphen separating start and end address from range.
2549 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2550 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2551
2552 // Parse out the ending address
2553 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2554
2555 // Parse out the space after the address.
2556 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2557 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2558
2559 // Save the range.
2560 memory_region_info.GetRange ().SetRangeBase (start_address);
2561 memory_region_info.GetRange ().SetRangeEnd (end_address);
2562
2563 // Parse out each permission entry.
2564 if (line_extractor.GetBytesLeft () < 4)
2565 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2566
2567 // Handle read permission.
2568 const char read_perm_char = line_extractor.GetChar ();
2569 if (read_perm_char == 'r')
2570 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2571 else
2572 {
2573 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2574 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2575 }
2576
2577 // Handle write permission.
2578 const char write_perm_char = line_extractor.GetChar ();
2579 if (write_perm_char == 'w')
2580 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2581 else
2582 {
2583 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2584 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2585 }
2586
2587 // Handle execute permission.
2588 const char exec_perm_char = line_extractor.GetChar ();
2589 if (exec_perm_char == 'x')
2590 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2591 else
2592 {
2593 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2594 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2595 }
2596
2597 return Error ();
2598}
2599
2600Error
2601NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2602{
2603 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2604 // with no perms if it is not mapped.
2605
2606 // Use an approach that reads memory regions from /proc/{pid}/maps.
2607 // Assume proc maps entries are in ascending order.
2608 // FIXME assert if we find differently.
2609 Mutex::Locker locker (m_mem_region_cache_mutex);
2610
2611 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2612 Error error;
2613
2614 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2615 {
2616 // We're done.
2617 error.SetErrorString ("unsupported");
2618 return error;
2619 }
2620
2621 // If our cache is empty, pull the latest. There should always be at least one memory region
2622 // if memory region handling is supported.
2623 if (m_mem_region_cache.empty ())
2624 {
2625 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2626 [&] (const std::string &line) -> bool
2627 {
2628 MemoryRegionInfo info;
2629 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2630 if (parse_error.Success ())
2631 {
2632 m_mem_region_cache.push_back (info);
2633 return true;
2634 }
2635 else
2636 {
2637 if (log)
2638 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2639 return false;
2640 }
2641 });
2642
2643 // If we had an error, we'll mark unsupported.
2644 if (error.Fail ())
2645 {
2646 m_supports_mem_region = LazyBool::eLazyBoolNo;
2647 return error;
2648 }
2649 else if (m_mem_region_cache.empty ())
2650 {
2651 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2652 // is supported. Assume we don't support map entries via procfs.
2653 if (log)
2654 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2655 m_supports_mem_region = LazyBool::eLazyBoolNo;
2656 error.SetErrorString ("not supported");
2657 return error;
2658 }
2659
2660 if (log)
2661 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2662
2663 // We support memory retrieval, remember that.
2664 m_supports_mem_region = LazyBool::eLazyBoolYes;
2665 }
2666 else
2667 {
2668 if (log)
2669 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2670 }
2671
2672 lldb::addr_t prev_base_address = 0;
2673
2674 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2675 // There can be a ton of regions on pthreads apps with lots of threads.
2676 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2677 {
2678 MemoryRegionInfo &proc_entry_info = *it;
2679
2680 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2681 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2682 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2683
2684 // If the target address comes before this entry, indicate distance to next region.
2685 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2686 {
2687 range_info.GetRange ().SetRangeBase (load_addr);
2688 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2689 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2690 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2691 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2692
2693 return error;
2694 }
2695 else if (proc_entry_info.GetRange ().Contains (load_addr))
2696 {
2697 // The target address is within the memory region we're processing here.
2698 range_info = proc_entry_info;
2699 return error;
2700 }
2701
2702 // The target memory address comes somewhere after the region we just parsed.
2703 }
2704
Tamas Berghammer09839c32015-07-03 09:30:19 +00002705 // If we made it here, we didn't find an entry that contained the given address. Return the
2706 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2707 // size.
2708 range_info.GetRange ().SetRangeBase (load_addr);
2709 switch (m_arch.GetAddressByteSize())
2710 {
2711 case 4:
2712 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2713 break;
2714 case 8:
2715 range_info.GetRange ().SetByteSize (0ull - load_addr);
2716 break;
2717 default:
2718 assert(false && "Unrecognized data byte size");
2719 break;
2720 }
2721 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2722 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2723 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002724 return error;
2725}
2726
2727void
2728NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2729{
2730 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2731 if (log)
2732 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2733
2734 {
2735 Mutex::Locker locker (m_mem_region_cache_mutex);
2736 if (log)
2737 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2738 m_mem_region_cache.clear ();
2739 }
2740}
2741
2742Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002743NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002744{
2745 // FIXME implementing this requires the equivalent of
2746 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2747 // functional ThreadPlans working with Native*Protocol.
2748#if 1
2749 return Error ("not implemented yet");
2750#else
2751 addr = LLDB_INVALID_ADDRESS;
2752
2753 unsigned prot = 0;
2754 if (permissions & lldb::ePermissionsReadable)
2755 prot |= eMmapProtRead;
2756 if (permissions & lldb::ePermissionsWritable)
2757 prot |= eMmapProtWrite;
2758 if (permissions & lldb::ePermissionsExecutable)
2759 prot |= eMmapProtExec;
2760
2761 // TODO implement this directly in NativeProcessLinux
2762 // (and lift to NativeProcessPOSIX if/when that class is
2763 // refactored out).
2764 if (InferiorCallMmap(this, addr, 0, size, prot,
2765 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2766 m_addr_to_mmap_size[addr] = size;
2767 return Error ();
2768 } else {
2769 addr = LLDB_INVALID_ADDRESS;
2770 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2771 }
2772#endif
2773}
2774
2775Error
2776NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2777{
2778 // FIXME see comments in AllocateMemory - required lower-level
2779 // bits not in place yet (ThreadPlans)
2780 return Error ("not implemented");
2781}
2782
2783lldb::addr_t
2784NativeProcessLinux::GetSharedLibraryInfoAddress ()
2785{
2786#if 1
2787 // punt on this for now
2788 return LLDB_INVALID_ADDRESS;
2789#else
2790 // Return the image info address for the exe module
2791#if 1
2792 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2793
2794 ModuleSP module_sp;
2795 Error error = GetExeModuleSP (module_sp);
2796 if (error.Fail ())
2797 {
2798 if (log)
2799 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2800 return LLDB_INVALID_ADDRESS;
2801 }
2802
2803 if (module_sp == nullptr)
2804 {
2805 if (log)
2806 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2807 return LLDB_INVALID_ADDRESS;
2808 }
2809
2810 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2811 if (object_file_sp == nullptr)
2812 {
2813 if (log)
2814 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2815 return LLDB_INVALID_ADDRESS;
2816 }
2817
2818 return obj_file_sp->GetImageInfoAddress();
2819#else
2820 Target *target = &GetTarget();
2821 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2822 Address addr = obj_file->GetImageInfoAddress(target);
2823
2824 if (addr.IsValid())
2825 return addr.GetLoadAddress(target);
2826 return LLDB_INVALID_ADDRESS;
2827#endif
2828#endif // punt on this for now
2829}
2830
2831size_t
2832NativeProcessLinux::UpdateThreads ()
2833{
2834 // The NativeProcessLinux monitoring threads are always up to date
2835 // with respect to thread state and they keep the thread list
2836 // populated properly. All this method needs to do is return the
2837 // thread count.
2838 Mutex::Locker locker (m_threads_mutex);
2839 return m_threads.size ();
2840}
2841
2842bool
2843NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2844{
2845 arch = m_arch;
2846 return true;
2847}
2848
2849Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002850NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002851{
2852 // FIXME put this behind a breakpoint protocol class that can be
2853 // set per architecture. Need ARM, MIPS support here.
2854 static const uint8_t g_i386_opcode [] = { 0xCC };
2855
2856 switch (m_arch.GetMachine ())
2857 {
2858 case llvm::Triple::x86:
2859 case llvm::Triple::x86_64:
2860 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2861 return Error ();
2862
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002863 case llvm::Triple::arm:
2864 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002865 case llvm::Triple::mips64:
2866 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002867 case llvm::Triple::mips:
2868 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002869 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002870 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002871 return Error ();
2872
Todd Fialaaf245d12014-06-30 21:05:18 +00002873 default:
2874 assert(false && "CPU type not supported!");
2875 return Error ("CPU type not supported");
2876 }
2877}
2878
2879Error
2880NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2881{
2882 if (hardware)
2883 return Error ("NativeProcessLinux does not support hardware breakpoints");
2884 else
2885 return SetSoftwareBreakpoint (addr, size);
2886}
2887
2888Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002889NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2890 size_t &actual_opcode_size,
2891 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002892{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002893 // FIXME put this behind a breakpoint protocol class that can be set per
2894 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002895 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002896 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2897 // linux kernel does otherwise.
2898 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002899 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002900 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002901 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002902 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002903
2904 switch (m_arch.GetMachine ())
2905 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002906 case llvm::Triple::aarch64:
2907 trap_opcode_bytes = g_aarch64_opcode;
2908 actual_opcode_size = sizeof(g_aarch64_opcode);
2909 return Error ();
2910
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002911 case llvm::Triple::arm:
2912 switch (trap_opcode_size_hint)
2913 {
2914 case 2:
2915 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2916 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2917 return Error ();
2918 case 4:
2919 trap_opcode_bytes = g_arm_breakpoint_opcode;
2920 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2921 return Error ();
2922 default:
2923 assert(false && "Unrecognised trap opcode size hint!");
2924 return Error ("Unrecognised trap opcode size hint!");
2925 }
2926
Todd Fialaaf245d12014-06-30 21:05:18 +00002927 case llvm::Triple::x86:
2928 case llvm::Triple::x86_64:
2929 trap_opcode_bytes = g_i386_opcode;
2930 actual_opcode_size = sizeof(g_i386_opcode);
2931 return Error ();
2932
Sagar Thakurce815e42015-06-03 10:14:24 +00002933 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002934 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002935 trap_opcode_bytes = g_mips64_opcode;
2936 actual_opcode_size = sizeof(g_mips64_opcode);
2937 return Error ();
2938
Sagar Thakurce815e42015-06-03 10:14:24 +00002939 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002940 case llvm::Triple::mips64el:
2941 trap_opcode_bytes = g_mips64el_opcode;
2942 actual_opcode_size = sizeof(g_mips64el_opcode);
2943 return Error ();
2944
Todd Fialaaf245d12014-06-30 21:05:18 +00002945 default:
2946 assert(false && "CPU type not supported!");
2947 return Error ("CPU type not supported");
2948 }
2949}
2950
2951#if 0
2952ProcessMessage::CrashReason
2953NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2954{
2955 ProcessMessage::CrashReason reason;
2956 assert(info->si_signo == SIGSEGV);
2957
2958 reason = ProcessMessage::eInvalidCrashReason;
2959
2960 switch (info->si_code)
2961 {
2962 default:
2963 assert(false && "unexpected si_code for SIGSEGV");
2964 break;
2965 case SI_KERNEL:
2966 // Linux will occasionally send spurious SI_KERNEL codes.
2967 // (this is poorly documented in sigaction)
2968 // One way to get this is via unaligned SIMD loads.
2969 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2970 break;
2971 case SEGV_MAPERR:
2972 reason = ProcessMessage::eInvalidAddress;
2973 break;
2974 case SEGV_ACCERR:
2975 reason = ProcessMessage::ePrivilegedAddress;
2976 break;
2977 }
2978
2979 return reason;
2980}
2981#endif
2982
2983
2984#if 0
2985ProcessMessage::CrashReason
2986NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2987{
2988 ProcessMessage::CrashReason reason;
2989 assert(info->si_signo == SIGILL);
2990
2991 reason = ProcessMessage::eInvalidCrashReason;
2992
2993 switch (info->si_code)
2994 {
2995 default:
2996 assert(false && "unexpected si_code for SIGILL");
2997 break;
2998 case ILL_ILLOPC:
2999 reason = ProcessMessage::eIllegalOpcode;
3000 break;
3001 case ILL_ILLOPN:
3002 reason = ProcessMessage::eIllegalOperand;
3003 break;
3004 case ILL_ILLADR:
3005 reason = ProcessMessage::eIllegalAddressingMode;
3006 break;
3007 case ILL_ILLTRP:
3008 reason = ProcessMessage::eIllegalTrap;
3009 break;
3010 case ILL_PRVOPC:
3011 reason = ProcessMessage::ePrivilegedOpcode;
3012 break;
3013 case ILL_PRVREG:
3014 reason = ProcessMessage::ePrivilegedRegister;
3015 break;
3016 case ILL_COPROC:
3017 reason = ProcessMessage::eCoprocessorError;
3018 break;
3019 case ILL_BADSTK:
3020 reason = ProcessMessage::eInternalStackError;
3021 break;
3022 }
3023
3024 return reason;
3025}
3026#endif
3027
3028#if 0
3029ProcessMessage::CrashReason
3030NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3031{
3032 ProcessMessage::CrashReason reason;
3033 assert(info->si_signo == SIGFPE);
3034
3035 reason = ProcessMessage::eInvalidCrashReason;
3036
3037 switch (info->si_code)
3038 {
3039 default:
3040 assert(false && "unexpected si_code for SIGFPE");
3041 break;
3042 case FPE_INTDIV:
3043 reason = ProcessMessage::eIntegerDivideByZero;
3044 break;
3045 case FPE_INTOVF:
3046 reason = ProcessMessage::eIntegerOverflow;
3047 break;
3048 case FPE_FLTDIV:
3049 reason = ProcessMessage::eFloatDivideByZero;
3050 break;
3051 case FPE_FLTOVF:
3052 reason = ProcessMessage::eFloatOverflow;
3053 break;
3054 case FPE_FLTUND:
3055 reason = ProcessMessage::eFloatUnderflow;
3056 break;
3057 case FPE_FLTRES:
3058 reason = ProcessMessage::eFloatInexactResult;
3059 break;
3060 case FPE_FLTINV:
3061 reason = ProcessMessage::eFloatInvalidOperation;
3062 break;
3063 case FPE_FLTSUB:
3064 reason = ProcessMessage::eFloatSubscriptRange;
3065 break;
3066 }
3067
3068 return reason;
3069}
3070#endif
3071
3072#if 0
3073ProcessMessage::CrashReason
3074NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3075{
3076 ProcessMessage::CrashReason reason;
3077 assert(info->si_signo == SIGBUS);
3078
3079 reason = ProcessMessage::eInvalidCrashReason;
3080
3081 switch (info->si_code)
3082 {
3083 default:
3084 assert(false && "unexpected si_code for SIGBUS");
3085 break;
3086 case BUS_ADRALN:
3087 reason = ProcessMessage::eIllegalAlignment;
3088 break;
3089 case BUS_ADRERR:
3090 reason = ProcessMessage::eIllegalAddress;
3091 break;
3092 case BUS_OBJERR:
3093 reason = ProcessMessage::eHardwareError;
3094 break;
3095 }
3096
3097 return reason;
3098}
3099#endif
3100
Todd Fialaaf245d12014-06-30 21:05:18 +00003101Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003102NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3103{
3104 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3105 // for it.
3106 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3107 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3108}
3109
3110Error
3111NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3112{
3113 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3114 // for it.
3115 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3116 return NativeProcessProtocol::RemoveWatchpoint(addr);
3117}
3118
3119Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003120NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003121{
Pavel Labathdf7c6992015-06-17 18:38:49 +00003122 if (ProcessVmReadvSupported()) {
3123 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3124 // this syscall if it is supported.
3125
3126 const ::pid_t pid = GetID();
3127
3128 struct iovec local_iov, remote_iov;
3129 local_iov.iov_base = buf;
3130 local_iov.iov_len = size;
3131 remote_iov.iov_base = reinterpret_cast<void *>(addr);
3132 remote_iov.iov_len = size;
3133
3134 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3135 const bool success = bytes_read == size;
3136
3137 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3138 if (log)
3139 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3140 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3141
3142 if (success)
3143 return Error();
3144 // else
3145 // the call failed for some reason, let's retry the read using ptrace api.
3146 }
3147
Pavel Labathc7512fd2015-06-26 10:14:12 +00003148 return DoOperation([&] { return DoReadMemory(GetID(), addr, buf, size, bytes_read); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003149}
3150
3151Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003152NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3153{
3154 Error error = ReadMemory(addr, buf, size, bytes_read);
3155 if (error.Fail()) return error;
3156 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3157}
3158
3159Error
3160NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003161{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003162 return DoOperation([&] { return DoWriteMemory(GetID(), addr, buf, size, bytes_written); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003163}
3164
Chaoren Lin97ccc292015-02-03 01:51:12 +00003165Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003166NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3167{
Todd Fialaaf245d12014-06-30 21:05:18 +00003168 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3169
3170 if (log)
3171 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3172 GetUnixSignals().GetSignalAsCString (signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00003173
3174
3175
3176 intptr_t data = 0;
3177
3178 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3179 data = signo;
3180
Pavel Labath4a9babb2015-06-30 17:04:49 +00003181 Error error = DoOperation([&] { return PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data); });
Pavel Labathc7512fd2015-06-26 10:14:12 +00003182
Todd Fialaaf245d12014-06-30 21:05:18 +00003183 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00003184 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
3185 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00003186}
3187
Chaoren Lin97ccc292015-02-03 01:51:12 +00003188Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003189NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3190{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003191 intptr_t data = 0;
3192
3193 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3194 data = signo;
3195
Pavel Labath4a9babb2015-06-30 17:04:49 +00003196 return DoOperation([&] { return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003197}
3198
Chaoren Lin97ccc292015-02-03 01:51:12 +00003199Error
3200NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003201{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003202 return DoOperation([&] { return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003203}
3204
Chaoren Lin97ccc292015-02-03 01:51:12 +00003205Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003206NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3207{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003208 return DoOperation([&] { return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003209}
3210
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003211Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003212NativeProcessLinux::Detach(lldb::tid_t tid)
3213{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003214 if (tid == LLDB_INVALID_THREAD_ID)
3215 return Error();
3216
Pavel Labath4a9babb2015-06-30 17:04:49 +00003217 return DoOperation([&] { return PtraceWrapper(PTRACE_DETACH, tid); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003218}
3219
3220bool
Chaoren Lind3173f32015-05-29 19:52:29 +00003221NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00003222{
Chaoren Lind3173f32015-05-29 19:52:29 +00003223 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00003224
3225 if (target_fd == -1)
3226 return false;
3227
Pavel Labath493c3a12015-02-04 10:36:57 +00003228 if (dup2(target_fd, fd) == -1)
3229 return false;
3230
3231 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003232}
3233
3234void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003235NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003236{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003237 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003238 error = m_monitor_up->Initialize();
3239 if (error.Fail()) {
3240 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003241 }
3242}
3243
Todd Fialaaf245d12014-06-30 21:05:18 +00003244bool
3245NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3246{
3247 for (auto thread_sp : m_threads)
3248 {
3249 assert (thread_sp && "thread list should not contain NULL threads");
3250 if (thread_sp->GetID () == thread_id)
3251 {
3252 // We have this thread.
3253 return true;
3254 }
3255 }
3256
3257 // We don't have this thread.
3258 return false;
3259}
3260
3261NativeThreadProtocolSP
3262NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3263{
3264 // CONSIDER organize threads by map - we can do better than linear.
3265 for (auto thread_sp : m_threads)
3266 {
3267 if (thread_sp->GetID () == thread_id)
3268 return thread_sp;
3269 }
3270
3271 // We don't have this thread.
3272 return NativeThreadProtocolSP ();
3273}
3274
3275bool
3276NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3277{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003278 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3279
3280 if (log)
3281 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3282
3283 bool found = false;
3284
Todd Fialaaf245d12014-06-30 21:05:18 +00003285 Mutex::Locker locker (m_threads_mutex);
3286 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3287 {
3288 if (*it && ((*it)->GetID () == thread_id))
3289 {
3290 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003291 found = true;
3292 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003293 }
3294 }
3295
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003296 // If we have a pending notification, remove this from the set.
3297 if (m_pending_notification_up)
3298 {
3299 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003300 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003301 }
3302
3303 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003304}
3305
3306NativeThreadProtocolSP
3307NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3308{
3309 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3310
3311 Mutex::Locker locker (m_threads_mutex);
3312
3313 if (log)
3314 {
3315 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3316 __FUNCTION__,
3317 GetID (),
3318 thread_id);
3319 }
3320
3321 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3322
3323 // If this is the first thread, save it as the current thread
3324 if (m_threads.empty ())
3325 SetCurrentThreadID (thread_id);
3326
3327 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3328 m_threads.push_back (thread_sp);
3329
3330 return thread_sp;
3331}
3332
Todd Fialaaf245d12014-06-30 21:05:18 +00003333Error
3334NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3335{
Todd Fiala75f47c32014-10-11 21:42:09 +00003336 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003337
3338 Error error;
3339
3340 // Get a linux thread pointer.
3341 if (!thread_sp)
3342 {
3343 error.SetErrorString ("null thread_sp");
3344 if (log)
3345 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3346 return error;
3347 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003348 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003349
3350 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003351 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003352 if (!context_sp)
3353 {
3354 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3355 if (log)
3356 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3357 return error;
3358 }
3359
3360 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003361 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003362 if (error.Fail ())
3363 {
3364 if (log)
3365 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3366 return error;
3367 }
3368 else
3369 {
3370 if (log)
3371 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3372 }
3373
3374 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00003375 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003376 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003377 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003378 {
3379 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003380 if (breakpoint_addr >= breakpoint_size)
3381 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003382 }
3383
3384 // Check if we stopped because of a breakpoint.
3385 NativeBreakpointSP breakpoint_sp;
3386 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3387 if (!error.Success () || !breakpoint_sp)
3388 {
3389 // We didn't find one at a software probe location. Nothing to do.
3390 if (log)
3391 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3392 return Error ();
3393 }
3394
3395 // If the breakpoint is not a software breakpoint, nothing to do.
3396 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3397 {
3398 if (log)
3399 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3400 return Error ();
3401 }
3402
3403 //
3404 // We have a software breakpoint and need to adjust the PC.
3405 //
3406
3407 // Sanity check.
3408 if (breakpoint_size == 0)
3409 {
3410 // Nothing to do! How did we get here?
3411 if (log)
3412 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);
3413 return Error ();
3414 }
3415
3416 // Change the program counter.
3417 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003418 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 +00003419
3420 error = context_sp->SetPC (breakpoint_addr);
3421 if (error.Fail ())
3422 {
3423 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003424 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 +00003425 return error;
3426 }
3427
3428 return error;
3429}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003430
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003431Error
3432NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3433{
3434 char maps_file_name[32];
3435 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3436
3437 FileSpec maps_file_spec(maps_file_name, false);
3438 if (!maps_file_spec.Exists()) {
3439 file_spec.Clear();
3440 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3441 }
3442
3443 FileSpec module_file_spec(module_path, true);
3444
3445 std::ifstream maps_file(maps_file_name);
3446 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3447 StringRef maps_data(maps_data_str.c_str());
3448
3449 while (!maps_data.empty())
3450 {
3451 StringRef maps_row;
3452 std::tie(maps_row, maps_data) = maps_data.split('\n');
3453
3454 SmallVector<StringRef, 16> maps_columns;
3455 maps_row.split(maps_columns, StringRef(" "), -1, false);
3456
3457 if (maps_columns.size() >= 6)
3458 {
3459 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3460 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3461 return Error();
3462 }
3463 }
3464
3465 file_spec.Clear();
3466 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3467 module_file_spec.GetFilename().AsCString(), GetID());
3468}
Pavel Labathc0765592015-05-06 10:46:34 +00003469
Pavel Labath5eb721e2015-05-07 08:30:31 +00003470Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003471NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3472{
3473 load_addr = LLDB_INVALID_ADDRESS;
3474 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3475 [&] (const std::string &line) -> bool
3476 {
3477 StringRef maps_row(line);
3478
3479 SmallVector<StringRef, 16> maps_columns;
3480 maps_row.split(maps_columns, StringRef(" "), -1, false);
3481
3482 if (maps_columns.size() < 6)
3483 {
3484 // Return true to continue reading the proc file
3485 return true;
3486 }
3487
3488 if (maps_columns[5] == file_name)
3489 {
3490 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3491 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3492
3493 // Return false to stop reading the proc file further
3494 return false;
3495 }
3496
3497 // Return true to continue reading the proc file
3498 return true;
3499 });
3500 return error;
3501}
3502
3503Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003504NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003505 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003506 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003507 bool error_when_already_running)
3508{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003509 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003510
3511 if (log)
3512 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3513 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003514
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003515 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3516 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003517
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003518 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003519 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003520 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003521
3522 lldbassert(!(error_when_already_running && !is_stopped));
3523
Pavel Labathc0765592015-05-06 10:46:34 +00003524 if (!is_stopped)
3525 {
3526 // It's not an error, just a log, if the error_when_already_running flag is not set.
3527 // This covers cases where, for instance, we're just trying to resume all threads
3528 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003529 if (log)
3530 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3531 __FUNCTION__,
3532 tid);
3533 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003534 }
3535
3536 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003537 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003538 // this thread to stop. This is potentially a buggy situation since
3539 // we're ostensibly waiting for threads to stop before we send out the
3540 // pending notification, and here we are resuming one before we send
3541 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003542 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003543 {
Pavel Labath108c3252015-05-12 09:03:18 +00003544 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 +00003545 }
3546
3547 // Request a resume. We expect this to be synchronous and the system
3548 // to reflect it is running after this completes.
3549 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003550 if (error.Success())
3551 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003552 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003553 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003554 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003555 __FUNCTION__, tid, error.AsCString ());
3556 }
3557
Pavel Labath5eb721e2015-05-07 08:30:31 +00003558 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003559}
3560
3561//===----------------------------------------------------------------------===//
3562
3563void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003564NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003565{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003566 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003567
Pavel Labath5eb721e2015-05-07 08:30:31 +00003568 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003569 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003570 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003571 __FUNCTION__, triggering_tid);
3572 }
3573
Pavel Labath337f3eb2015-05-08 08:57:45 +00003574 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003575
Pavel Labath5eb721e2015-05-07 08:30:31 +00003576 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003577 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003578 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003579 }
3580}
3581
3582void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003583NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003584{
3585 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3586 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003587 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3588
3589 // Clear any temporary breakpoints we used to implement software single stepping.
3590 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3591 {
3592 Error error = RemoveBreakpoint (thread_info.second);
3593 if (error.Fail())
3594 if (log)
3595 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3596 __FUNCTION__, thread_info.first, error.AsCString());
3597 }
3598 m_threads_stepping_with_breakpoint.clear();
3599
3600 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003601 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3602 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003603 m_pending_notification_up.reset();
3604 }
3605}
3606
Pavel Labathc0765592015-05-06 10:46:34 +00003607void
3608NativeProcessLinux::RequestStopOnAllRunningThreads()
3609{
3610 // Request a stop for all the thread stops that need to be stopped
3611 // and are not already known to be stopped. Keep a list of all the
3612 // threads from which we still need to hear a stop reply.
3613
3614 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003615 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003616 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003617 // We only care about running threads
3618 if (StateIsStoppedState(thread_sp->GetState(), true))
3619 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003620
Pavel Labath108c3252015-05-12 09:03:18 +00003621 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3622 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003623 }
3624
3625 // Set the wait list to the set of tids for which we requested stops.
3626 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3627}
3628
Pavel Labathc0765592015-05-06 10:46:34 +00003629
Pavel Labath5eb721e2015-05-07 08:30:31 +00003630Error
3631NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003632{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003633 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3634
3635 if (log)
3636 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3637 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3638
Pavel Labathc0765592015-05-06 10:46:34 +00003639 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003640 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3641 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003642
3643 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003644 auto& context = thread_sp->GetThreadContext();
3645 const auto stop_was_requested = context.stop_requested;
3646 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003647
3648 // If we have a pending notification, remove this from the set.
3649 if (m_pending_notification_up)
3650 {
3651 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003652 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003653 }
3654
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003655 Error error;
3656 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003657 {
3658 // We can end up here if stop was initiated by LLGS but by this time a
3659 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003660 if (log)
3661 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003662 error = context.request_resume_function (tid, true);
3663 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003664 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003665 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3666 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003667 }
3668 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003669 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003670}
3671
3672void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003673NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003674{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003675 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3676 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003677 {
3678 // Yikes - we've already got a pending signal notification in progress.
3679 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003680 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 +00003681 __FUNCTION__,
3682 m_pending_notification_up->triggering_tid,
3683 notification_up->triggering_tid);
3684 }
3685 m_pending_notification_up = std::move(notification_up);
3686
Pavel Labath108c3252015-05-12 09:03:18 +00003687 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003688
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003689 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003690}
3691
3692void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003693NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003694{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003695 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3696
3697 if (log)
3698 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3699
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003700 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3701 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003702
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003703 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003704 {
3705 // We will need to wait for this new thread to stop as well before firing the
3706 // notification.
3707 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003708 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003709 }
3710}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003711
3712Error
Pavel Labathc7512fd2015-06-26 10:14:12 +00003713NativeProcessLinux::DoOperation(const Operation &op)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003714{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003715 return m_monitor_up->DoOperation(op);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003716}
3717
3718// Wrapper for ptrace to catch errors and log calls.
3719// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003720Error
3721NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003722{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003723 Error error;
3724 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003725
3726 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3727
3728 PtraceDisplayBytes(req, data, data_size);
3729
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003730 errno = 0;
3731 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003732 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003733 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003734 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003735
Pavel Labath4a9babb2015-06-30 17:04:49 +00003736 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003737 error.SetErrorToErrno();
3738
Pavel Labath4a9babb2015-06-30 17:04:49 +00003739 if (result)
3740 *result = ret;
3741
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003742 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003743 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003744
3745 PtraceDisplayBytes(req, data, data_size);
3746
3747 if (log && error.GetError() != 0)
3748 {
3749 const char* str;
3750 switch (error.GetError())
3751 {
3752 case ESRCH: str = "ESRCH"; break;
3753 case EINVAL: str = "EINVAL"; break;
3754 case EBUSY: str = "EBUSY"; break;
3755 case EPERM: str = "EPERM"; break;
3756 default: str = error.AsCString();
3757 }
3758 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3759 }
3760
Pavel Labath4a9babb2015-06-30 17:04:49 +00003761 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003762}