blob: ae25fb4b4f18c9102f237490a208c2ee9aa7eda2 [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
Pavel Labath235c8402015-07-08 09:08:53 +0000827NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000828 ProcessLaunchInfo &launch_info,
829 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000830 NativeProcessProtocolSP &native_process_sp)
831{
832 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
833
Pavel Labath235c8402015-07-08 09:08:53 +0000834 lldb::ModuleSP exe_module_sp;
835 PlatformSP platform_sp (Platform::GetHostPlatform ());
836 Error error = platform_sp->ResolveExecutable(
837 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
838 exe_module_sp,
839 nullptr);
840
841 if (! error.Success())
842 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000843
844 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000845 FileSpec working_dir{launch_info.GetWorkingDirectory()};
846 if (working_dir &&
847 (!working_dir.ResolvePath() ||
848 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000849 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000850 error.SetErrorStringWithFormat ("No such file or directory: %s",
851 working_dir.GetCString());
852 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000853 }
854
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000855 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000856
Chaoren Lind3173f32015-05-29 19:52:29 +0000857 // Default of empty will mean to use existing open file descriptors.
858 FileSpec stdin_file_spec{};
859 FileSpec stdout_file_spec{};
860 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000861
862 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000863 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000864 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000865
866 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000867 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000868 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000869
870 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000871 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000872 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000873
874 if (log)
875 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000876 if (stdin_file_spec)
877 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
878 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000879 else
880 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
881
Chaoren Lind3173f32015-05-29 19:52:29 +0000882 if (stdout_file_spec)
883 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
884 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000885 else
886 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
887
Chaoren Lind3173f32015-05-29 19:52:29 +0000888 if (stderr_file_spec)
889 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
890 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000891 else
892 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
893 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000894
895 // Create the NativeProcessLinux in launch mode.
896 native_process_sp.reset (new NativeProcessLinux ());
897
898 if (log)
899 {
900 int i = 0;
901 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
902 {
903 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
904 ++i;
905 }
906 }
907
908 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
909 {
910 native_process_sp.reset ();
911 error.SetErrorStringWithFormat ("failed to register the native delegate");
912 return error;
913 }
914
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000915 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath235c8402015-07-08 09:08:53 +0000916 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000917 launch_info.GetArguments ().GetConstArgumentVector (),
918 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000919 stdin_file_spec,
920 stdout_file_spec,
921 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000922 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000923 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 error);
925
926 if (error.Fail ())
927 {
928 native_process_sp.reset ();
929 if (log)
930 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
931 return error;
932 }
933
934 launch_info.SetProcessID (native_process_sp->GetID ());
935
936 return error;
937}
938
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000939Error
Pavel Labath235c8402015-07-08 09:08:53 +0000940NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000941 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000942 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000943 NativeProcessProtocolSP &native_process_sp)
944{
945 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
946 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
947 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
948
949 // Grab the current platform architecture. This should be Linux,
950 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000951 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000952 if (!platform_sp)
953 return Error("failed to get a valid default platform");
954
955 // Retrieve the architecture for the running process.
956 ArchSpec process_arch;
957 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
958 if (!error.Success ())
959 return error;
960
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000961 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000962
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000963 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000964 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000965 error.SetErrorStringWithFormat ("failed to register the native delegate");
966 return error;
967 }
968
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000969 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000970 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000971 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000972
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000973 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000974 return error;
975}
976
977// -----------------------------------------------------------------------------
978// Public Instance Methods
979// -----------------------------------------------------------------------------
980
981NativeProcessLinux::NativeProcessLinux () :
982 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
983 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000984 m_supports_mem_region (eLazyBoolCalculate),
985 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +0000986 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000987{
988}
989
990//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000991// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
992// Refer to Monitor and Operation classes to see why this is necessary.
993//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000994void
995NativeProcessLinux::LaunchInferior (
996 Module *module,
997 const char *argv[],
998 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000999 const FileSpec &stdin_file_spec,
1000 const FileSpec &stdout_file_spec,
1001 const FileSpec &stderr_file_spec,
1002 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001003 const ProcessLaunchInfo &launch_info,
1004 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001005{
1006 if (module)
1007 m_arch = module->GetArchitecture ();
1008
Chaoren Linfa03ad22015-02-03 01:50:42 +00001009 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001010
1011 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +00001012 new LaunchArgs(module, argv, envp,
1013 stdin_file_spec,
1014 stdout_file_spec,
1015 stderr_file_spec,
1016 working_dir,
1017 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001018
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001019 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001020 if (!error.Success ())
1021 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001022}
1023
1024void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001025NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001026{
1027 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1028 if (log)
1029 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1030
1031 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001032 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001033 if (!platform_sp)
1034 {
1035 if (log)
1036 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1037 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001038 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001039 }
1040
1041 // Gather info about the process.
1042 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001043 if (!platform_sp->GetProcessInfo (pid, process_info))
1044 {
1045 if (log)
1046 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1047 error.SetErrorString ("failed to get process info");
1048 return;
1049 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001050
1051 // Resolve the executable module
1052 ModuleSP exe_module_sp;
1053 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001054 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001055 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001056 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001057 if (!error.Success())
1058 return;
1059
1060 // Set the architecture to the exe architecture.
1061 m_arch = exe_module_sp->GetArchitecture();
1062 if (log)
1063 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1064
1065 m_pid = pid;
1066 SetState(eStateAttaching);
1067
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001068 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001069 if (!error.Success ())
1070 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001071}
1072
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001073void
1074NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001075{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001076 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001077}
1078
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001079::pid_t
1080NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001081{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001082 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001083
1084 const char **argv = args->m_argv;
1085 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +00001086 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +00001087
1088 lldb_utility::PseudoTerminal terminal;
1089 const size_t err_len = 1024;
1090 char err_str[err_len];
1091 lldb::pid_t pid;
1092 NativeThreadProtocolSP thread_sp;
1093
1094 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001095
1096 // Propagate the environment if one is not supplied.
1097 if (envp == NULL || envp[0] == NULL)
1098 envp = const_cast<const char **>(environ);
1099
1100 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1101 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001102 error.SetErrorToGenericError();
1103 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1104 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001105 }
1106
1107 // Recognized child exit status codes.
1108 enum {
1109 ePtraceFailed = 1,
1110 eDupStdinFailed,
1111 eDupStdoutFailed,
1112 eDupStderrFailed,
1113 eChdirFailed,
1114 eExecFailed,
1115 eSetGidFailed
1116 };
1117
1118 // Child process.
1119 if (pid == 0)
1120 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001121 // FIXME consider opening a pipe between parent/child and have this forked child
1122 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001123
Todd Fiala75f47c32014-10-11 21:42:09 +00001124 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001125 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001126 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001127 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001128
Pavel Labath493c3a12015-02-04 10:36:57 +00001129 // terminal has already dupped the tty descriptors to stdin/out/err.
1130 // This closes original fd from which they were copied (and avoids
1131 // leaking descriptors to the debugged process.
1132 terminal.CloseSlaveFileDescriptor();
1133
Todd Fialaaf245d12014-06-30 21:05:18 +00001134 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001135 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001136 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001137
1138 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001139 if (setpgid(0, 0) != 0)
1140 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001141 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001142 // Don't allow this to prevent an inferior exec.
1143 }
1144
1145 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +00001146 if (args->m_stdin_file_spec)
1147 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001148 exit(eDupStdinFailed);
1149
Chaoren Lind3173f32015-05-29 19:52:29 +00001150 if (args->m_stdout_file_spec)
1151 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001152 exit(eDupStdoutFailed);
1153
Chaoren Lind3173f32015-05-29 19:52:29 +00001154 if (args->m_stderr_file_spec)
1155 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001156 exit(eDupStderrFailed);
1157
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001158 // Close everything besides stdin, stdout, and stderr that has no file
1159 // action to avoid leaking
1160 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1161 if (!args->m_launch_info.GetFileActionForFD(fd))
1162 close(fd);
1163
Todd Fialaaf245d12014-06-30 21:05:18 +00001164 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +00001165 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +00001166 exit(eChdirFailed);
1167
Todd Fiala0bce1b62014-08-17 00:10:50 +00001168 // Disable ASLR if requested.
1169 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1170 {
1171 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1172 if (old_personality == -1)
1173 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001174 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001175 }
1176 else
1177 {
1178 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1179 if (new_personality == -1)
1180 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001181 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001182 }
1183 else
1184 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001185 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001186 }
1187 }
1188 }
1189
Todd Fiala75f47c32014-10-11 21:42:09 +00001190 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001191 execve(argv[0],
1192 const_cast<char *const *>(argv),
1193 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001194
1195 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001196 exit(eExecFailed);
1197 }
1198
Todd Fiala75f47c32014-10-11 21:42:09 +00001199 //
1200 // This is the parent code here.
1201 //
1202 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1203
Todd Fialaaf245d12014-06-30 21:05:18 +00001204 // Wait for the child process to trap on its call to execve.
1205 ::pid_t wpid;
1206 int status;
1207 if ((wpid = waitpid(pid, &status, 0)) < 0)
1208 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001209 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001210 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001211 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1212 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001213
1214 // Mark the inferior as invalid.
1215 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001216 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001217
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001218 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001219 }
1220 else if (WIFEXITED(status))
1221 {
1222 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001223 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001224 switch (WEXITSTATUS(status))
1225 {
1226 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001227 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001228 break;
1229 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001230 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001231 break;
1232 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001233 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001234 break;
1235 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001236 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001237 break;
1238 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001239 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001240 break;
1241 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001242 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001243 break;
1244 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001245 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001246 break;
1247 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001248 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001249 break;
1250 }
1251
1252 if (log)
1253 {
1254 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1255 __FUNCTION__,
1256 WEXITSTATUS(status));
1257 }
1258
1259 // Mark the inferior as invalid.
1260 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001261 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001262
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001263 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001264 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001265 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001266 "Could not sync with inferior process.");
1267
1268 if (log)
1269 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1270
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001271 error = SetDefaultPtraceOpts(pid);
1272 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001273 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001274 if (log)
1275 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001276 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001277
1278 // Mark the inferior as invalid.
1279 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001280 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001281
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001282 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001283 }
1284
1285 // Release the master terminal descriptor and pass it off to the
1286 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001287 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1288 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001289
1290 // Set the terminal fd to be in non blocking mode (it simplifies the
1291 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1292 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001293 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1294 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001295 {
1296 if (log)
1297 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001298 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001299
1300 // Mark the inferior as invalid.
1301 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001302 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001303
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001304 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001305 }
1306
1307 if (log)
1308 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1309
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001310 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001312 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001313 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001314
1315 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001316 SetCurrentThreadID (thread_sp->GetID ());
1317 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001318
Todd Fialaaf245d12014-06-30 21:05:18 +00001319 if (log)
1320 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001321 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001322 {
1323 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1324 }
1325 else
1326 {
1327 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001328 __FUNCTION__, error.AsCString ());
1329 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001330 }
1331 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001332 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001333}
1334
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001335::pid_t
1336NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001337{
Todd Fialaaf245d12014-06-30 21:05:18 +00001338 lldb::ThreadSP inferior;
1339 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1340
1341 // Use a map to keep track of the threads which we have attached/need to attach.
1342 Host::TidMap tids_to_attach;
1343 if (pid <= 1)
1344 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001345 error.SetErrorToGenericError();
1346 error.SetErrorString("Attaching to process 1 is not allowed.");
1347 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001348 }
1349
1350 while (Host::FindProcessThreads(pid, tids_to_attach))
1351 {
1352 for (Host::TidMap::iterator it = tids_to_attach.begin();
1353 it != tids_to_attach.end();)
1354 {
1355 if (it->second == false)
1356 {
1357 lldb::tid_t tid = it->first;
1358
1359 // Attach to the requested process.
1360 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001361 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001362 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001363 {
1364 // No such thread. The thread may have exited.
1365 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001366 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001367 {
1368 it = tids_to_attach.erase(it);
1369 continue;
1370 }
1371 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001372 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001373 }
1374
1375 int status;
1376 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1377 // At this point we should have a thread stopped if waitpid succeeds.
1378 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1379 {
1380 // No such thread. The thread may have exited.
1381 // More error handling may be needed.
1382 if (errno == ESRCH)
1383 {
1384 it = tids_to_attach.erase(it);
1385 continue;
1386 }
1387 else
1388 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001389 error.SetErrorToErrno();
1390 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001391 }
1392 }
1393
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001394 error = SetDefaultPtraceOpts(tid);
1395 if (error.Fail())
1396 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001397
1398 if (log)
1399 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1400
1401 it->second = true;
1402
1403 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001404 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001405 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001406
1407 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001408 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001409 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001410 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001411 }
1412
1413 // move the loop forward
1414 ++it;
1415 }
1416 }
1417
1418 if (tids_to_attach.size() > 0)
1419 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001420 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001421 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001422 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001423 }
1424 else
1425 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001426 error.SetErrorToGenericError();
1427 error.SetErrorString("No such process.");
1428 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001429 }
1430
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001431 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001432}
1433
Chaoren Lin97ccc292015-02-03 01:51:12 +00001434Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001435NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1436{
1437 long ptrace_opts = 0;
1438
1439 // Have the child raise an event on exit. This is used to keep the child in
1440 // limbo until it is destroyed.
1441 ptrace_opts |= PTRACE_O_TRACEEXIT;
1442
1443 // Have the tracer trace threads which spawn in the inferior process.
1444 // TODO: if we want to support tracing the inferiors' child, add the
1445 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1446 ptrace_opts |= PTRACE_O_TRACECLONE;
1447
1448 // Have the tracer notify us before execve returns
1449 // (needed to disable legacy SIGTRAP generation)
1450 ptrace_opts |= PTRACE_O_TRACEEXEC;
1451
Pavel Labath4a9babb2015-06-30 17:04:49 +00001452 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +00001453}
1454
1455static ExitType convert_pid_status_to_exit_type (int status)
1456{
1457 if (WIFEXITED (status))
1458 return ExitType::eExitTypeExit;
1459 else if (WIFSIGNALED (status))
1460 return ExitType::eExitTypeSignal;
1461 else if (WIFSTOPPED (status))
1462 return ExitType::eExitTypeStop;
1463 else
1464 {
1465 // We don't know what this is.
1466 return ExitType::eExitTypeInvalid;
1467 }
1468}
1469
1470static int convert_pid_status_to_return_code (int status)
1471{
1472 if (WIFEXITED (status))
1473 return WEXITSTATUS (status);
1474 else if (WIFSIGNALED (status))
1475 return WTERMSIG (status);
1476 else if (WIFSTOPPED (status))
1477 return WSTOPSIG (status);
1478 else
1479 {
1480 // We don't know what this is.
1481 return ExitType::eExitTypeInvalid;
1482 }
1483}
1484
Pavel Labath1107b5a2015-04-17 14:07:49 +00001485// Handles all waitpid events from the inferior process.
1486void
1487NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001488 bool exited,
1489 int signal,
1490 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001491{
1492 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1493
Todd Fialaaf245d12014-06-30 21:05:18 +00001494 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001495 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001496
1497 // Handle when the thread exits.
1498 if (exited)
1499 {
1500 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001501 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 +00001502
1503 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001504 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001505
1506 if (is_main_thread)
1507 {
1508 // We only set the exit status and notify the delegate if we haven't already set the process
1509 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1510 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001511 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001512 if (!already_notified)
1513 {
1514 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001515 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 +00001516 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001517 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001518
1519 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001520 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001521 }
1522 else
1523 {
1524 if (log)
1525 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1526 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001527 }
1528 else
1529 {
1530 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1531 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1532 // and we would have done an all-stop then.
1533 if (log)
1534 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 +00001535 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001536 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001537 }
1538
1539 // Get details on the signal raised.
1540 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001541 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001542 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001543 {
1544 // We have retrieved the signal info. Dispatch appropriately.
1545 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001546 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001547 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001548 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001549 }
1550 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001551 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001552 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001553 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001554 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001555 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1556 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1557 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1558 // generally not needed (one use case is debugging background task being managed by a
1559 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1560 // stop which happens before the group stop. This done by MonitorSignal and works
1561 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001562 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001563 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);
1564 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001565 }
1566 else
1567 {
1568 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1569
1570 // A return value of ESRCH means the thread/process is no longer on the system,
1571 // so it was killed somehow outside of our control. Either way, we can't do anything
1572 // with it anymore.
1573
Todd Fialaaf245d12014-06-30 21:05:18 +00001574 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001575 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001576
1577 if (log)
1578 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001579 __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 +00001580
1581 if (is_main_thread)
1582 {
1583 // Notify the delegate - our process is not available but appears to have been killed outside
1584 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001585 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1586 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001587 }
1588 else
1589 {
1590 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1591 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001592 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 +00001593 }
1594 }
1595 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001596}
1597
1598void
Pavel Labath426bdf82015-04-28 07:51:52 +00001599NativeProcessLinux::WaitForNewThread(::pid_t tid)
1600{
1601 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1602
1603 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1604
1605 if (new_thread_sp)
1606 {
1607 // We are already tracking the thread - we got the event on the new thread (see
1608 // MonitorSignal) before this one. We are done.
1609 return;
1610 }
1611
1612 // The thread is not tracked yet, let's wait for it to appear.
1613 int status = -1;
1614 ::pid_t wait_pid;
1615 do
1616 {
1617 if (log)
1618 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1619 wait_pid = waitpid(tid, &status, __WALL);
1620 }
1621 while (wait_pid == -1 && errno == EINTR);
1622 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1623 // some checks just in case.
1624 if (wait_pid != tid) {
1625 if (log)
1626 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1627 // The only way I know of this could happen is if the whole process was
1628 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1629 return;
1630 }
1631 if (WIFEXITED(status))
1632 {
1633 if (log)
1634 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1635 // Also a very improbable event.
1636 return;
1637 }
1638
1639 siginfo_t info;
1640 Error error = GetSignalInfo(tid, &info);
1641 if (error.Fail())
1642 {
1643 if (log)
1644 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1645 return;
1646 }
1647
1648 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1649 {
1650 // We should be getting a thread creation signal here, but we received something
1651 // else. There isn't much we can do about it now, so we will just log that. Since the
1652 // thread is alive and we are receiving events from it, we shall pretend that it was
1653 // created properly.
1654 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);
1655 }
1656
1657 if (log)
1658 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1659 __FUNCTION__, GetID (), tid);
1660
1661 new_thread_sp = AddThread(tid);
1662 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1663 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001664 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001665}
1666
1667void
Todd Fialaaf245d12014-06-30 21:05:18 +00001668NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1669{
1670 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1671 const bool is_main_thread = (pid == GetID ());
1672
1673 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1674 if (!info)
1675 return;
1676
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001677 Mutex::Locker locker (m_threads_mutex);
1678
Todd Fialaaf245d12014-06-30 21:05:18 +00001679 // See if we can find a thread for this signal.
1680 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1681 if (!thread_sp)
1682 {
1683 if (log)
1684 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1685 }
1686
1687 switch (info->si_code)
1688 {
1689 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1690 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1691 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1692
1693 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1694 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001695 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001696 // creation.
1697 // We don't want to do anything with the parent thread so we just resume it. In case we
1698 // want to implement "break on thread creation" functionality, we would need to stop
1699 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001700
Pavel Labath426bdf82015-04-28 07:51:52 +00001701 unsigned long event_message = 0;
1702 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001703 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001704 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001705 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 +00001706 } else
1707 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001708
Pavel Labath5fd24c62015-04-23 09:04:35 +00001709 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001710 break;
1711 }
1712
1713 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001714 {
1715 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001716 if (log)
1717 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001718
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001719 // Exec clears any pending notifications.
1720 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001721
1722 // 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 +00001723 if (log)
1724 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1725
1726 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001727 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001728 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1729 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001730 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001731 main_thread_sp = thread_sp;
1732 if (log)
1733 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001734 }
1735 else
1736 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001737 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001738 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001739 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001740 }
1741 }
1742
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001743 m_threads.clear ();
1744
1745 if (main_thread_sp)
1746 {
1747 m_threads.push_back (main_thread_sp);
1748 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001749 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001750 }
1751 else
1752 {
1753 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1754 if (log)
1755 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1756 }
1757
Chaoren Linfa03ad22015-02-03 01:50:42 +00001758 // Tell coordinator about about the "new" (since exec) stopped main thread.
1759 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001760 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001761
1762 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1763 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001764 // Let our delegate know we have just exec'd.
1765 NotifyDidExec ();
1766
1767 // If we have a main thread, indicate we are stopped.
1768 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001769
1770 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001771 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001772
Todd Fialaaf245d12014-06-30 21:05:18 +00001773 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001774 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001775
1776 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1777 {
1778 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001779 // We don't want to do anything with the thread so we just resume it. In case we
1780 // want to implement "break on thread exit" functionality, we would need to stop
1781 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001782
Todd Fialaaf245d12014-06-30 21:05:18 +00001783 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001784 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001785 data = -1;
1786
1787 if (log)
1788 {
1789 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1790 __FUNCTION__,
1791 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1792 pid,
1793 is_main_thread ? "is main thread" : "not main thread");
1794 }
1795
Todd Fialaaf245d12014-06-30 21:05:18 +00001796 if (is_main_thread)
1797 {
1798 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001799 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001800
Pavel Labath6e351632015-05-15 13:30:59 +00001801 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001802
1803 break;
1804 }
1805
1806 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001807 case TRAP_TRACE: // We receive this on single stepping.
1808 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001809 if (thread_sp)
1810 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001811 // If a watchpoint was hit, report it
1812 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001813 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001814 if (error.Fail() && log)
1815 log->Printf("NativeProcessLinux::%s() "
1816 "received error while checking for watchpoint hits, "
1817 "pid = %" PRIu64 " error = %s",
1818 __FUNCTION__, pid, error.AsCString());
1819 if (wp_index != LLDB_INVALID_INDEX32)
1820 {
1821 MonitorWatchpoint(pid, thread_sp, wp_index);
1822 break;
1823 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001824 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001825 // Otherwise, report step over
1826 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001827 break;
1828
1829 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001830#if defined __mips__
1831 // For mips there is no special signal for watchpoint
1832 // So we check for watchpoint in kernel trap
1833 if (thread_sp)
1834 {
1835 // If a watchpoint was hit, report it
1836 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001837 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001838 if (error.Fail() && log)
1839 log->Printf("NativeProcessLinux::%s() "
1840 "received error while checking for watchpoint hits, "
1841 "pid = %" PRIu64 " error = %s",
1842 __FUNCTION__, pid, error.AsCString());
1843 if (wp_index != LLDB_INVALID_INDEX32)
1844 {
1845 MonitorWatchpoint(pid, thread_sp, wp_index);
1846 break;
1847 }
1848 }
1849 // NO BREAK
1850#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001851 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001852 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001853 break;
1854
1855 case SIGTRAP:
1856 case (SIGTRAP | 0x80):
1857 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001858 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1859
Todd Fialaaf245d12014-06-30 21:05:18 +00001860 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001861 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001862 break;
1863
1864 default:
1865 assert(false && "Unexpected SIGTRAP code!");
1866 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001867 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1868 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001869 break;
1870
1871 }
1872}
1873
1874void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001875NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1876{
1877 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1878 if (log)
1879 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1880 __FUNCTION__, pid);
1881
1882 if (thread_sp)
1883 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1884
1885 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001886 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001887
1888 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1889 // This would have already happened at the time the Resume() with step operation was signaled.
1890 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1891 // once all running threads have checked in as stopped.
1892 SetCurrentThreadID(pid);
1893 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001894 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001895}
1896
1897void
1898NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1899{
1900 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1901 if (log)
1902 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1903 __FUNCTION__, pid);
1904
1905 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001906 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001907
1908 // Mark the thread as stopped at breakpoint.
1909 if (thread_sp)
1910 {
1911 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1912 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1913 if (error.Fail())
1914 if (log)
1915 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1916 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001917
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001918 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001919 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001920 }
1921 else
1922 if (log)
1923 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1924 "warning, cannot process software breakpoint since no thread metadata",
1925 __FUNCTION__, pid);
1926
1927
1928 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001929 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001930}
1931
1932void
1933NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1934{
1935 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1936 if (log)
1937 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1938 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1939 __FUNCTION__, pid, wp_index);
1940
1941 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001942 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001943
1944 // Mark the thread as stopped at watchpoint.
1945 // The address is at (lldb::addr_t)info->si_addr if we need it.
1946 lldbassert(thread_sp && "thread_sp cannot be NULL");
1947 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1948
1949 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001950 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001951}
1952
1953void
Todd Fialaaf245d12014-06-30 21:05:18 +00001954NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1955{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001956 assert (info && "null info");
1957 if (!info)
1958 return;
1959
1960 const int signo = info->si_signo;
1961 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001962
1963 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1964
1965 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1966 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1967 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1968 //
1969 // IOW, user generated signals never generate what we consider to be a
1970 // "crash".
1971 //
1972 // Similarly, ACK signals generated by this monitor.
1973
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001974 Mutex::Locker locker (m_threads_mutex);
1975
Todd Fialaaf245d12014-06-30 21:05:18 +00001976 // See if we can find a thread for this signal.
1977 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1978 if (!thread_sp)
1979 {
1980 if (log)
1981 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1982 }
1983
1984 // Handle the signal.
1985 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1986 {
1987 if (log)
1988 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1989 __FUNCTION__,
1990 GetUnixSignals ().GetSignalAsCString (signo),
1991 signo,
1992 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1993 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001994 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001995 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001996 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001997
Todd Fiala58a2f662014-08-12 17:02:07 +00001998 // Check for new thread notification.
1999 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2000 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002001 // A new thread creation is being signaled. This is one of two parts that come in
2002 // a non-deterministic order. This code handles the case where the new thread event comes
2003 // before the event on the parent thread. For the opposite case see code in
2004 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002005 if (log)
2006 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2007 __FUNCTION__, GetID (), pid);
2008
Pavel Labath5fd24c62015-04-23 09:04:35 +00002009 thread_sp = AddThread(pid);
2010 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2011 // We can now resume the newly created thread.
2012 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2013 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002014 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002015 // Done handling.
2016 return;
2017 }
2018
2019 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002020 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002021 {
2022 // This is a tgkill()-based stop.
2023 if (thread_sp)
2024 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002025 if (log)
2026 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2027 __FUNCTION__,
2028 GetID (),
2029 pid);
2030
Chaoren Linaab58632015-02-03 01:50:57 +00002031 // Check that we're not already marked with a stop reason.
2032 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2033 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2034 // and that, without an intervening resume, we received another stop. It is more likely
2035 // that we are missing the marking of a run state somewhere if we find that the thread was
2036 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002037 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2038 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002039
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002040 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002041 if (!StateIsStoppedState (thread_state, false))
2042 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002043 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2044 // Generally, these are not important stops and we don't want to report them as
2045 // they are just used to stop other threads when one thread (the one with the
2046 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2047 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2048 // leave the signal intact if this is the thread that was chosen as the
2049 // triggering thread.
2050 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002051 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002052 else
2053 linux_thread_sp->SetStoppedBySignal(0);
2054
Chaoren Linaab58632015-02-03 01:50:57 +00002055 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002056 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002057 }
2058 else
2059 {
2060 if (log)
2061 {
2062 // Retrieve the signal name if the thread was stopped by a signal.
2063 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002064 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002065 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2066 if (!signal_name)
2067 signal_name = "<no-signal-name>";
2068
2069 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",
2070 __FUNCTION__,
2071 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002072 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002073 StateAsCString (thread_state),
2074 stop_signo,
2075 signal_name);
2076 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002077 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002078 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002079 }
2080
2081 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002082 return;
2083 }
2084
2085 if (log)
2086 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2087
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002088 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002089 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002090
Pavel Labathc4e25c92015-05-29 10:13:03 +00002091 if (thread_sp)
2092 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002093
2094 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002095 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002096}
2097
Tamas Berghammere7708682015-04-22 10:00:23 +00002098namespace {
2099
2100struct EmulatorBaton
2101{
2102 NativeProcessLinux* m_process;
2103 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002104
Pavel Labath6648fcc2015-04-27 09:21:14 +00002105 // eRegisterKindDWARF -> RegsiterValue
2106 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2107
2108 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002109 m_process(process), m_reg_context(reg_context) {}
2110};
2111
2112} // anonymous namespace
2113
2114static size_t
2115ReadMemoryCallback (EmulateInstruction *instruction,
2116 void *baton,
2117 const EmulateInstruction::Context &context,
2118 lldb::addr_t addr,
2119 void *dst,
2120 size_t length)
2121{
2122 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2123
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002124 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002125 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2126 return bytes_read;
2127}
2128
2129static bool
2130ReadRegisterCallback (EmulateInstruction *instruction,
2131 void *baton,
2132 const RegisterInfo *reg_info,
2133 RegisterValue &reg_value)
2134{
2135 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2136
Pavel Labath6648fcc2015-04-27 09:21:14 +00002137 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2138 if (it != emulator_baton->m_register_values.end())
2139 {
2140 reg_value = it->second;
2141 return true;
2142 }
2143
Tamas Berghammere7708682015-04-22 10:00:23 +00002144 // The emulator only fill in the dwarf regsiter numbers (and in some case
2145 // the generic register numbers). Get the full register info from the
2146 // register context based on the dwarf register numbers.
2147 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2148 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2149
2150 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002151 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002152 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002153
Pavel Labath6648fcc2015-04-27 09:21:14 +00002154 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002155}
2156
2157static bool
2158WriteRegisterCallback (EmulateInstruction *instruction,
2159 void *baton,
2160 const EmulateInstruction::Context &context,
2161 const RegisterInfo *reg_info,
2162 const RegisterValue &reg_value)
2163{
2164 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002165 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002166 return true;
2167}
2168
2169static size_t
2170WriteMemoryCallback (EmulateInstruction *instruction,
2171 void *baton,
2172 const EmulateInstruction::Context &context,
2173 lldb::addr_t addr,
2174 const void *dst,
2175 size_t length)
2176{
2177 return length;
2178}
2179
2180static lldb::addr_t
2181ReadFlags (NativeRegisterContext* regsiter_context)
2182{
2183 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2184 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2185 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2186}
2187
2188Error
2189NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2190{
2191 Error error;
2192 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2193
2194 std::unique_ptr<EmulateInstruction> emulator_ap(
2195 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2196
2197 if (emulator_ap == nullptr)
2198 return Error("Instruction emulator not found!");
2199
2200 EmulatorBaton baton(this, register_context_sp.get());
2201 emulator_ap->SetBaton(&baton);
2202 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2203 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2204 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2205 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2206
2207 if (!emulator_ap->ReadInstruction())
2208 return Error("Read instruction failed!");
2209
Pavel Labath6648fcc2015-04-27 09:21:14 +00002210 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2211
2212 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2213 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2214
2215 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2216 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2217
Tamas Berghammere7708682015-04-22 10:00:23 +00002218 lldb::addr_t next_pc;
2219 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002220 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002221 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002222 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2223 next_pc = pc_it->second.GetAsUInt64();
2224
2225 if (flags_it != baton.m_register_values.end())
2226 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002227 else
2228 next_flags = ReadFlags (register_context_sp.get());
2229 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002230 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002231 {
2232 // Emulate instruction failed and it haven't changed PC. Advance PC
2233 // with the size of the current opcode because the emulation of all
2234 // PC modifying instruction should be successful. The failure most
2235 // likely caused by a not supported instruction which don't modify PC.
2236 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2237 next_flags = ReadFlags (register_context_sp.get());
2238 }
2239 else
2240 {
2241 // The instruction emulation failed after it modified the PC. It is an
2242 // unknown error where we can't continue because the next instruction is
2243 // modifying the PC but we don't know how.
2244 return Error ("Instruction emulation failed unexpectedly.");
2245 }
2246
2247 if (m_arch.GetMachine() == llvm::Triple::arm)
2248 {
2249 if (next_flags & 0x20)
2250 {
2251 // Thumb mode
2252 error = SetSoftwareBreakpoint(next_pc, 2);
2253 }
2254 else
2255 {
2256 // Arm mode
2257 error = SetSoftwareBreakpoint(next_pc, 4);
2258 }
2259 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002260 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002261 || m_arch.GetMachine() == llvm::Triple::mips64el
2262 || m_arch.GetMachine() == llvm::Triple::mips
2263 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002264 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002265 else
2266 {
2267 // No size hint is given for the next breakpoint
2268 error = SetSoftwareBreakpoint(next_pc, 0);
2269 }
2270
Tamas Berghammere7708682015-04-22 10:00:23 +00002271 if (error.Fail())
2272 return error;
2273
2274 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2275
2276 return Error();
2277}
2278
2279bool
2280NativeProcessLinux::SupportHardwareSingleStepping() const
2281{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002282 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002283 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
2284 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002285 return false;
2286 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002287}
2288
Todd Fialaaf245d12014-06-30 21:05:18 +00002289Error
2290NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2291{
Todd Fialaaf245d12014-06-30 21:05:18 +00002292 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2293 if (log)
2294 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2295
Tamas Berghammere7708682015-04-22 10:00:23 +00002296 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002297
Pavel Labath45f5cb32015-05-05 15:05:50 +00002298 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002299 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002300
Tamas Berghammere7708682015-04-22 10:00:23 +00002301 if (software_single_step)
2302 {
2303 for (auto thread_sp : m_threads)
2304 {
2305 assert (thread_sp && "thread list should not contain NULL threads");
2306
2307 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2308 if (action == nullptr)
2309 continue;
2310
2311 if (action->state == eStateStepping)
2312 {
2313 Error error = SetupSoftwareSingleStepping(thread_sp);
2314 if (error.Fail())
2315 return error;
2316 }
2317 }
2318 }
2319
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002320 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002321 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002322 assert (thread_sp && "thread list should not contain NULL threads");
2323
2324 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2325
2326 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002327 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002328 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002329 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2330 __FUNCTION__, GetID (), thread_sp->GetID ());
2331 continue;
2332 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002333
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002334 if (log)
2335 {
2336 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2337 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2338 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002339
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002340 switch (action->state)
2341 {
2342 case eStateRunning:
2343 {
2344 // Run the thread, possibly feeding it the signal.
2345 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002346 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002347 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2348 {
2349 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2350 // Pass this signal number on to the inferior to handle.
2351 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2352 if (resume_result.Success())
2353 SetState(eStateRunning, true);
2354 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002355 },
2356 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002357 break;
2358 }
2359
2360 case eStateStepping:
2361 {
2362 // Request the step.
2363 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002364 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002365 [=](lldb::tid_t tid_to_step, bool supress_signal)
2366 {
2367 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002368
Pavel Labathc0765592015-05-06 10:46:34 +00002369 Error step_result;
2370 if (software_single_step)
2371 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2372 else
2373 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002374
Pavel Labathc0765592015-05-06 10:46:34 +00002375 assert (step_result.Success() && "SingleStep() failed");
2376 if (step_result.Success())
2377 SetState(eStateStepping, true);
2378 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002379 },
2380 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002381 break;
2382 }
2383
2384 case eStateSuspended:
2385 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002386 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002387
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002388 default:
2389 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2390 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002391 }
2392 }
2393
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002394 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002395}
2396
2397Error
2398NativeProcessLinux::Halt ()
2399{
2400 Error error;
2401
Todd Fialaaf245d12014-06-30 21:05:18 +00002402 if (kill (GetID (), SIGSTOP) != 0)
2403 error.SetErrorToErrno ();
2404
2405 return error;
2406}
2407
2408Error
2409NativeProcessLinux::Detach ()
2410{
2411 Error error;
2412
2413 // Tell ptrace to detach from the process.
2414 if (GetID () != LLDB_INVALID_PROCESS_ID)
2415 error = Detach (GetID ());
2416
2417 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00002418 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002419
2420 // No error.
2421 return error;
2422}
2423
2424Error
2425NativeProcessLinux::Signal (int signo)
2426{
2427 Error error;
2428
2429 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2430 if (log)
2431 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2432 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2433
2434 if (kill(GetID(), signo))
2435 error.SetErrorToErrno();
2436
2437 return error;
2438}
2439
2440Error
Chaoren Line9547b82015-02-03 01:51:00 +00002441NativeProcessLinux::Interrupt ()
2442{
2443 // Pick a running thread (or if none, a not-dead stopped thread) as
2444 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002445 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2446
2447 NativeThreadProtocolSP running_thread_sp;
2448 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002449
2450 if (log)
2451 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2452
Pavel Labath45f5cb32015-05-05 15:05:50 +00002453 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002454 Mutex::Locker locker (m_threads_mutex);
2455
2456 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002457 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002458 // The thread shouldn't be null but lets just cover that here.
2459 if (!thread_sp)
2460 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002461
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002462 // If we have a running or stepping thread, we'll call that the
2463 // target of the interrupt.
2464 const auto thread_state = thread_sp->GetState ();
2465 if (thread_state == eStateRunning ||
2466 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002467 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002468 running_thread_sp = thread_sp;
2469 break;
2470 }
2471 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2472 {
2473 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2474 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002475 }
2476 }
2477
2478 if (!running_thread_sp && !stopped_thread_sp)
2479 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002480 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002481 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002482 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002483
Chaoren Line9547b82015-02-03 01:51:00 +00002484 return error;
2485 }
2486
2487 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2488
2489 if (log)
2490 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2491 __FUNCTION__,
2492 GetID (),
2493 running_thread_sp ? "running" : "stopped",
2494 deferred_signal_thread_sp->GetID ());
2495
Pavel Labathed89c7f2015-05-06 12:22:37 +00002496 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002497
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002498 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002499}
2500
2501Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002502NativeProcessLinux::Kill ()
2503{
2504 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2505 if (log)
2506 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2507
2508 Error error;
2509
2510 switch (m_state)
2511 {
2512 case StateType::eStateInvalid:
2513 case StateType::eStateExited:
2514 case StateType::eStateCrashed:
2515 case StateType::eStateDetached:
2516 case StateType::eStateUnloaded:
2517 // Nothing to do - the process is already dead.
2518 if (log)
2519 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2520 return error;
2521
2522 case StateType::eStateConnected:
2523 case StateType::eStateAttaching:
2524 case StateType::eStateLaunching:
2525 case StateType::eStateStopped:
2526 case StateType::eStateRunning:
2527 case StateType::eStateStepping:
2528 case StateType::eStateSuspended:
2529 // We can try to kill a process in these states.
2530 break;
2531 }
2532
2533 if (kill (GetID (), SIGKILL) != 0)
2534 {
2535 error.SetErrorToErrno ();
2536 return error;
2537 }
2538
2539 return error;
2540}
2541
2542static Error
2543ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2544{
2545 memory_region_info.Clear();
2546
2547 StringExtractor line_extractor (maps_line.c_str ());
2548
2549 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2550 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2551
2552 // Parse out the starting address
2553 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2554
2555 // Parse out hyphen separating start and end address from range.
2556 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2557 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2558
2559 // Parse out the ending address
2560 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2561
2562 // Parse out the space after the address.
2563 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2564 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2565
2566 // Save the range.
2567 memory_region_info.GetRange ().SetRangeBase (start_address);
2568 memory_region_info.GetRange ().SetRangeEnd (end_address);
2569
2570 // Parse out each permission entry.
2571 if (line_extractor.GetBytesLeft () < 4)
2572 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2573
2574 // Handle read permission.
2575 const char read_perm_char = line_extractor.GetChar ();
2576 if (read_perm_char == 'r')
2577 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2578 else
2579 {
2580 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2581 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2582 }
2583
2584 // Handle write permission.
2585 const char write_perm_char = line_extractor.GetChar ();
2586 if (write_perm_char == 'w')
2587 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2588 else
2589 {
2590 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2591 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2592 }
2593
2594 // Handle execute permission.
2595 const char exec_perm_char = line_extractor.GetChar ();
2596 if (exec_perm_char == 'x')
2597 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2598 else
2599 {
2600 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2601 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2602 }
2603
2604 return Error ();
2605}
2606
2607Error
2608NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2609{
2610 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2611 // with no perms if it is not mapped.
2612
2613 // Use an approach that reads memory regions from /proc/{pid}/maps.
2614 // Assume proc maps entries are in ascending order.
2615 // FIXME assert if we find differently.
2616 Mutex::Locker locker (m_mem_region_cache_mutex);
2617
2618 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2619 Error error;
2620
2621 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2622 {
2623 // We're done.
2624 error.SetErrorString ("unsupported");
2625 return error;
2626 }
2627
2628 // If our cache is empty, pull the latest. There should always be at least one memory region
2629 // if memory region handling is supported.
2630 if (m_mem_region_cache.empty ())
2631 {
2632 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2633 [&] (const std::string &line) -> bool
2634 {
2635 MemoryRegionInfo info;
2636 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2637 if (parse_error.Success ())
2638 {
2639 m_mem_region_cache.push_back (info);
2640 return true;
2641 }
2642 else
2643 {
2644 if (log)
2645 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2646 return false;
2647 }
2648 });
2649
2650 // If we had an error, we'll mark unsupported.
2651 if (error.Fail ())
2652 {
2653 m_supports_mem_region = LazyBool::eLazyBoolNo;
2654 return error;
2655 }
2656 else if (m_mem_region_cache.empty ())
2657 {
2658 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2659 // is supported. Assume we don't support map entries via procfs.
2660 if (log)
2661 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2662 m_supports_mem_region = LazyBool::eLazyBoolNo;
2663 error.SetErrorString ("not supported");
2664 return error;
2665 }
2666
2667 if (log)
2668 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2669
2670 // We support memory retrieval, remember that.
2671 m_supports_mem_region = LazyBool::eLazyBoolYes;
2672 }
2673 else
2674 {
2675 if (log)
2676 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2677 }
2678
2679 lldb::addr_t prev_base_address = 0;
2680
2681 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2682 // There can be a ton of regions on pthreads apps with lots of threads.
2683 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2684 {
2685 MemoryRegionInfo &proc_entry_info = *it;
2686
2687 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2688 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2689 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2690
2691 // If the target address comes before this entry, indicate distance to next region.
2692 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2693 {
2694 range_info.GetRange ().SetRangeBase (load_addr);
2695 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2696 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2697 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2698 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2699
2700 return error;
2701 }
2702 else if (proc_entry_info.GetRange ().Contains (load_addr))
2703 {
2704 // The target address is within the memory region we're processing here.
2705 range_info = proc_entry_info;
2706 return error;
2707 }
2708
2709 // The target memory address comes somewhere after the region we just parsed.
2710 }
2711
Tamas Berghammer09839c32015-07-03 09:30:19 +00002712 // If we made it here, we didn't find an entry that contained the given address. Return the
2713 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2714 // size.
2715 range_info.GetRange ().SetRangeBase (load_addr);
2716 switch (m_arch.GetAddressByteSize())
2717 {
2718 case 4:
2719 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2720 break;
2721 case 8:
2722 range_info.GetRange ().SetByteSize (0ull - load_addr);
2723 break;
2724 default:
2725 assert(false && "Unrecognized data byte size");
2726 break;
2727 }
2728 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2729 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2730 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002731 return error;
2732}
2733
2734void
2735NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2736{
2737 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2738 if (log)
2739 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2740
2741 {
2742 Mutex::Locker locker (m_mem_region_cache_mutex);
2743 if (log)
2744 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2745 m_mem_region_cache.clear ();
2746 }
2747}
2748
2749Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002750NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002751{
2752 // FIXME implementing this requires the equivalent of
2753 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2754 // functional ThreadPlans working with Native*Protocol.
2755#if 1
2756 return Error ("not implemented yet");
2757#else
2758 addr = LLDB_INVALID_ADDRESS;
2759
2760 unsigned prot = 0;
2761 if (permissions & lldb::ePermissionsReadable)
2762 prot |= eMmapProtRead;
2763 if (permissions & lldb::ePermissionsWritable)
2764 prot |= eMmapProtWrite;
2765 if (permissions & lldb::ePermissionsExecutable)
2766 prot |= eMmapProtExec;
2767
2768 // TODO implement this directly in NativeProcessLinux
2769 // (and lift to NativeProcessPOSIX if/when that class is
2770 // refactored out).
2771 if (InferiorCallMmap(this, addr, 0, size, prot,
2772 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2773 m_addr_to_mmap_size[addr] = size;
2774 return Error ();
2775 } else {
2776 addr = LLDB_INVALID_ADDRESS;
2777 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2778 }
2779#endif
2780}
2781
2782Error
2783NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2784{
2785 // FIXME see comments in AllocateMemory - required lower-level
2786 // bits not in place yet (ThreadPlans)
2787 return Error ("not implemented");
2788}
2789
2790lldb::addr_t
2791NativeProcessLinux::GetSharedLibraryInfoAddress ()
2792{
2793#if 1
2794 // punt on this for now
2795 return LLDB_INVALID_ADDRESS;
2796#else
2797 // Return the image info address for the exe module
2798#if 1
2799 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2800
2801 ModuleSP module_sp;
2802 Error error = GetExeModuleSP (module_sp);
2803 if (error.Fail ())
2804 {
2805 if (log)
2806 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2807 return LLDB_INVALID_ADDRESS;
2808 }
2809
2810 if (module_sp == nullptr)
2811 {
2812 if (log)
2813 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2814 return LLDB_INVALID_ADDRESS;
2815 }
2816
2817 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2818 if (object_file_sp == nullptr)
2819 {
2820 if (log)
2821 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2822 return LLDB_INVALID_ADDRESS;
2823 }
2824
2825 return obj_file_sp->GetImageInfoAddress();
2826#else
2827 Target *target = &GetTarget();
2828 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2829 Address addr = obj_file->GetImageInfoAddress(target);
2830
2831 if (addr.IsValid())
2832 return addr.GetLoadAddress(target);
2833 return LLDB_INVALID_ADDRESS;
2834#endif
2835#endif // punt on this for now
2836}
2837
2838size_t
2839NativeProcessLinux::UpdateThreads ()
2840{
2841 // The NativeProcessLinux monitoring threads are always up to date
2842 // with respect to thread state and they keep the thread list
2843 // populated properly. All this method needs to do is return the
2844 // thread count.
2845 Mutex::Locker locker (m_threads_mutex);
2846 return m_threads.size ();
2847}
2848
2849bool
2850NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2851{
2852 arch = m_arch;
2853 return true;
2854}
2855
2856Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002857NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002858{
2859 // FIXME put this behind a breakpoint protocol class that can be
2860 // set per architecture. Need ARM, MIPS support here.
2861 static const uint8_t g_i386_opcode [] = { 0xCC };
2862
2863 switch (m_arch.GetMachine ())
2864 {
2865 case llvm::Triple::x86:
2866 case llvm::Triple::x86_64:
2867 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2868 return Error ();
2869
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002870 case llvm::Triple::arm:
2871 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002872 case llvm::Triple::mips64:
2873 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002874 case llvm::Triple::mips:
2875 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002876 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002877 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002878 return Error ();
2879
Todd Fialaaf245d12014-06-30 21:05:18 +00002880 default:
2881 assert(false && "CPU type not supported!");
2882 return Error ("CPU type not supported");
2883 }
2884}
2885
2886Error
2887NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2888{
2889 if (hardware)
2890 return Error ("NativeProcessLinux does not support hardware breakpoints");
2891 else
2892 return SetSoftwareBreakpoint (addr, size);
2893}
2894
2895Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002896NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2897 size_t &actual_opcode_size,
2898 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002899{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002900 // FIXME put this behind a breakpoint protocol class that can be set per
2901 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002902 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002903 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2904 // linux kernel does otherwise.
2905 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002906 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002907 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002908 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002909 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002910
2911 switch (m_arch.GetMachine ())
2912 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002913 case llvm::Triple::aarch64:
2914 trap_opcode_bytes = g_aarch64_opcode;
2915 actual_opcode_size = sizeof(g_aarch64_opcode);
2916 return Error ();
2917
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002918 case llvm::Triple::arm:
2919 switch (trap_opcode_size_hint)
2920 {
2921 case 2:
2922 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2923 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2924 return Error ();
2925 case 4:
2926 trap_opcode_bytes = g_arm_breakpoint_opcode;
2927 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2928 return Error ();
2929 default:
2930 assert(false && "Unrecognised trap opcode size hint!");
2931 return Error ("Unrecognised trap opcode size hint!");
2932 }
2933
Todd Fialaaf245d12014-06-30 21:05:18 +00002934 case llvm::Triple::x86:
2935 case llvm::Triple::x86_64:
2936 trap_opcode_bytes = g_i386_opcode;
2937 actual_opcode_size = sizeof(g_i386_opcode);
2938 return Error ();
2939
Sagar Thakurce815e42015-06-03 10:14:24 +00002940 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002941 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002942 trap_opcode_bytes = g_mips64_opcode;
2943 actual_opcode_size = sizeof(g_mips64_opcode);
2944 return Error ();
2945
Sagar Thakurce815e42015-06-03 10:14:24 +00002946 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002947 case llvm::Triple::mips64el:
2948 trap_opcode_bytes = g_mips64el_opcode;
2949 actual_opcode_size = sizeof(g_mips64el_opcode);
2950 return Error ();
2951
Todd Fialaaf245d12014-06-30 21:05:18 +00002952 default:
2953 assert(false && "CPU type not supported!");
2954 return Error ("CPU type not supported");
2955 }
2956}
2957
2958#if 0
2959ProcessMessage::CrashReason
2960NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2961{
2962 ProcessMessage::CrashReason reason;
2963 assert(info->si_signo == SIGSEGV);
2964
2965 reason = ProcessMessage::eInvalidCrashReason;
2966
2967 switch (info->si_code)
2968 {
2969 default:
2970 assert(false && "unexpected si_code for SIGSEGV");
2971 break;
2972 case SI_KERNEL:
2973 // Linux will occasionally send spurious SI_KERNEL codes.
2974 // (this is poorly documented in sigaction)
2975 // One way to get this is via unaligned SIMD loads.
2976 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2977 break;
2978 case SEGV_MAPERR:
2979 reason = ProcessMessage::eInvalidAddress;
2980 break;
2981 case SEGV_ACCERR:
2982 reason = ProcessMessage::ePrivilegedAddress;
2983 break;
2984 }
2985
2986 return reason;
2987}
2988#endif
2989
2990
2991#if 0
2992ProcessMessage::CrashReason
2993NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2994{
2995 ProcessMessage::CrashReason reason;
2996 assert(info->si_signo == SIGILL);
2997
2998 reason = ProcessMessage::eInvalidCrashReason;
2999
3000 switch (info->si_code)
3001 {
3002 default:
3003 assert(false && "unexpected si_code for SIGILL");
3004 break;
3005 case ILL_ILLOPC:
3006 reason = ProcessMessage::eIllegalOpcode;
3007 break;
3008 case ILL_ILLOPN:
3009 reason = ProcessMessage::eIllegalOperand;
3010 break;
3011 case ILL_ILLADR:
3012 reason = ProcessMessage::eIllegalAddressingMode;
3013 break;
3014 case ILL_ILLTRP:
3015 reason = ProcessMessage::eIllegalTrap;
3016 break;
3017 case ILL_PRVOPC:
3018 reason = ProcessMessage::ePrivilegedOpcode;
3019 break;
3020 case ILL_PRVREG:
3021 reason = ProcessMessage::ePrivilegedRegister;
3022 break;
3023 case ILL_COPROC:
3024 reason = ProcessMessage::eCoprocessorError;
3025 break;
3026 case ILL_BADSTK:
3027 reason = ProcessMessage::eInternalStackError;
3028 break;
3029 }
3030
3031 return reason;
3032}
3033#endif
3034
3035#if 0
3036ProcessMessage::CrashReason
3037NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3038{
3039 ProcessMessage::CrashReason reason;
3040 assert(info->si_signo == SIGFPE);
3041
3042 reason = ProcessMessage::eInvalidCrashReason;
3043
3044 switch (info->si_code)
3045 {
3046 default:
3047 assert(false && "unexpected si_code for SIGFPE");
3048 break;
3049 case FPE_INTDIV:
3050 reason = ProcessMessage::eIntegerDivideByZero;
3051 break;
3052 case FPE_INTOVF:
3053 reason = ProcessMessage::eIntegerOverflow;
3054 break;
3055 case FPE_FLTDIV:
3056 reason = ProcessMessage::eFloatDivideByZero;
3057 break;
3058 case FPE_FLTOVF:
3059 reason = ProcessMessage::eFloatOverflow;
3060 break;
3061 case FPE_FLTUND:
3062 reason = ProcessMessage::eFloatUnderflow;
3063 break;
3064 case FPE_FLTRES:
3065 reason = ProcessMessage::eFloatInexactResult;
3066 break;
3067 case FPE_FLTINV:
3068 reason = ProcessMessage::eFloatInvalidOperation;
3069 break;
3070 case FPE_FLTSUB:
3071 reason = ProcessMessage::eFloatSubscriptRange;
3072 break;
3073 }
3074
3075 return reason;
3076}
3077#endif
3078
3079#if 0
3080ProcessMessage::CrashReason
3081NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3082{
3083 ProcessMessage::CrashReason reason;
3084 assert(info->si_signo == SIGBUS);
3085
3086 reason = ProcessMessage::eInvalidCrashReason;
3087
3088 switch (info->si_code)
3089 {
3090 default:
3091 assert(false && "unexpected si_code for SIGBUS");
3092 break;
3093 case BUS_ADRALN:
3094 reason = ProcessMessage::eIllegalAlignment;
3095 break;
3096 case BUS_ADRERR:
3097 reason = ProcessMessage::eIllegalAddress;
3098 break;
3099 case BUS_OBJERR:
3100 reason = ProcessMessage::eHardwareError;
3101 break;
3102 }
3103
3104 return reason;
3105}
3106#endif
3107
Todd Fialaaf245d12014-06-30 21:05:18 +00003108Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003109NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3110{
3111 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3112 // for it.
3113 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3114 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3115}
3116
3117Error
3118NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3119{
3120 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3121 // for it.
3122 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3123 return NativeProcessProtocol::RemoveWatchpoint(addr);
3124}
3125
3126Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003127NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003128{
Pavel Labathdf7c6992015-06-17 18:38:49 +00003129 if (ProcessVmReadvSupported()) {
3130 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3131 // this syscall if it is supported.
3132
3133 const ::pid_t pid = GetID();
3134
3135 struct iovec local_iov, remote_iov;
3136 local_iov.iov_base = buf;
3137 local_iov.iov_len = size;
3138 remote_iov.iov_base = reinterpret_cast<void *>(addr);
3139 remote_iov.iov_len = size;
3140
3141 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3142 const bool success = bytes_read == size;
3143
3144 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3145 if (log)
3146 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3147 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3148
3149 if (success)
3150 return Error();
3151 // else
3152 // the call failed for some reason, let's retry the read using ptrace api.
3153 }
3154
Pavel Labathc7512fd2015-06-26 10:14:12 +00003155 return DoOperation([&] { return DoReadMemory(GetID(), addr, buf, size, bytes_read); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003156}
3157
3158Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003159NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3160{
3161 Error error = ReadMemory(addr, buf, size, bytes_read);
3162 if (error.Fail()) return error;
3163 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3164}
3165
3166Error
3167NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003168{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003169 return DoOperation([&] { return DoWriteMemory(GetID(), addr, buf, size, bytes_written); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003170}
3171
Chaoren Lin97ccc292015-02-03 01:51:12 +00003172Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003173NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3174{
Todd Fialaaf245d12014-06-30 21:05:18 +00003175 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3176
3177 if (log)
3178 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3179 GetUnixSignals().GetSignalAsCString (signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00003180
3181
3182
3183 intptr_t data = 0;
3184
3185 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3186 data = signo;
3187
Pavel Labath4a9babb2015-06-30 17:04:49 +00003188 Error error = DoOperation([&] { return PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data); });
Pavel Labathc7512fd2015-06-26 10:14:12 +00003189
Todd Fialaaf245d12014-06-30 21:05:18 +00003190 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00003191 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
3192 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00003193}
3194
Chaoren Lin97ccc292015-02-03 01:51:12 +00003195Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003196NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3197{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003198 intptr_t data = 0;
3199
3200 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3201 data = signo;
3202
Pavel Labath4a9babb2015-06-30 17:04:49 +00003203 return DoOperation([&] { return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003204}
3205
Chaoren Lin97ccc292015-02-03 01:51:12 +00003206Error
3207NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003208{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003209 return DoOperation([&] { return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003210}
3211
Chaoren Lin97ccc292015-02-03 01:51:12 +00003212Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003213NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3214{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003215 return DoOperation([&] { return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003216}
3217
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003218Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003219NativeProcessLinux::Detach(lldb::tid_t tid)
3220{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003221 if (tid == LLDB_INVALID_THREAD_ID)
3222 return Error();
3223
Pavel Labath4a9babb2015-06-30 17:04:49 +00003224 return DoOperation([&] { return PtraceWrapper(PTRACE_DETACH, tid); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003225}
3226
3227bool
Chaoren Lind3173f32015-05-29 19:52:29 +00003228NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00003229{
Chaoren Lind3173f32015-05-29 19:52:29 +00003230 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00003231
3232 if (target_fd == -1)
3233 return false;
3234
Pavel Labath493c3a12015-02-04 10:36:57 +00003235 if (dup2(target_fd, fd) == -1)
3236 return false;
3237
3238 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003239}
3240
3241void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003242NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003243{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003244 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003245 error = m_monitor_up->Initialize();
3246 if (error.Fail()) {
3247 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003248 }
3249}
3250
Todd Fialaaf245d12014-06-30 21:05:18 +00003251bool
3252NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3253{
3254 for (auto thread_sp : m_threads)
3255 {
3256 assert (thread_sp && "thread list should not contain NULL threads");
3257 if (thread_sp->GetID () == thread_id)
3258 {
3259 // We have this thread.
3260 return true;
3261 }
3262 }
3263
3264 // We don't have this thread.
3265 return false;
3266}
3267
3268NativeThreadProtocolSP
3269NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3270{
3271 // CONSIDER organize threads by map - we can do better than linear.
3272 for (auto thread_sp : m_threads)
3273 {
3274 if (thread_sp->GetID () == thread_id)
3275 return thread_sp;
3276 }
3277
3278 // We don't have this thread.
3279 return NativeThreadProtocolSP ();
3280}
3281
3282bool
3283NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3284{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003285 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3286
3287 if (log)
3288 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3289
3290 bool found = false;
3291
Todd Fialaaf245d12014-06-30 21:05:18 +00003292 Mutex::Locker locker (m_threads_mutex);
3293 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3294 {
3295 if (*it && ((*it)->GetID () == thread_id))
3296 {
3297 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003298 found = true;
3299 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003300 }
3301 }
3302
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003303 // If we have a pending notification, remove this from the set.
3304 if (m_pending_notification_up)
3305 {
3306 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003307 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003308 }
3309
3310 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003311}
3312
3313NativeThreadProtocolSP
3314NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3315{
3316 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3317
3318 Mutex::Locker locker (m_threads_mutex);
3319
3320 if (log)
3321 {
3322 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3323 __FUNCTION__,
3324 GetID (),
3325 thread_id);
3326 }
3327
3328 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3329
3330 // If this is the first thread, save it as the current thread
3331 if (m_threads.empty ())
3332 SetCurrentThreadID (thread_id);
3333
3334 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3335 m_threads.push_back (thread_sp);
3336
3337 return thread_sp;
3338}
3339
Todd Fialaaf245d12014-06-30 21:05:18 +00003340Error
3341NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3342{
Todd Fiala75f47c32014-10-11 21:42:09 +00003343 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003344
3345 Error error;
3346
3347 // Get a linux thread pointer.
3348 if (!thread_sp)
3349 {
3350 error.SetErrorString ("null thread_sp");
3351 if (log)
3352 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3353 return error;
3354 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003355 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003356
3357 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003358 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003359 if (!context_sp)
3360 {
3361 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3362 if (log)
3363 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3364 return error;
3365 }
3366
3367 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003368 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003369 if (error.Fail ())
3370 {
3371 if (log)
3372 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3373 return error;
3374 }
3375 else
3376 {
3377 if (log)
3378 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3379 }
3380
3381 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00003382 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003383 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003384 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003385 {
3386 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003387 if (breakpoint_addr >= breakpoint_size)
3388 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003389 }
3390
3391 // Check if we stopped because of a breakpoint.
3392 NativeBreakpointSP breakpoint_sp;
3393 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3394 if (!error.Success () || !breakpoint_sp)
3395 {
3396 // We didn't find one at a software probe location. Nothing to do.
3397 if (log)
3398 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3399 return Error ();
3400 }
3401
3402 // If the breakpoint is not a software breakpoint, nothing to do.
3403 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3404 {
3405 if (log)
3406 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3407 return Error ();
3408 }
3409
3410 //
3411 // We have a software breakpoint and need to adjust the PC.
3412 //
3413
3414 // Sanity check.
3415 if (breakpoint_size == 0)
3416 {
3417 // Nothing to do! How did we get here?
3418 if (log)
3419 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);
3420 return Error ();
3421 }
3422
3423 // Change the program counter.
3424 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003425 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 +00003426
3427 error = context_sp->SetPC (breakpoint_addr);
3428 if (error.Fail ())
3429 {
3430 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003431 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 +00003432 return error;
3433 }
3434
3435 return error;
3436}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003437
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003438Error
3439NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3440{
3441 char maps_file_name[32];
3442 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3443
3444 FileSpec maps_file_spec(maps_file_name, false);
3445 if (!maps_file_spec.Exists()) {
3446 file_spec.Clear();
3447 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3448 }
3449
3450 FileSpec module_file_spec(module_path, true);
3451
3452 std::ifstream maps_file(maps_file_name);
3453 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3454 StringRef maps_data(maps_data_str.c_str());
3455
3456 while (!maps_data.empty())
3457 {
3458 StringRef maps_row;
3459 std::tie(maps_row, maps_data) = maps_data.split('\n');
3460
3461 SmallVector<StringRef, 16> maps_columns;
3462 maps_row.split(maps_columns, StringRef(" "), -1, false);
3463
3464 if (maps_columns.size() >= 6)
3465 {
3466 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3467 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3468 return Error();
3469 }
3470 }
3471
3472 file_spec.Clear();
3473 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3474 module_file_spec.GetFilename().AsCString(), GetID());
3475}
Pavel Labathc0765592015-05-06 10:46:34 +00003476
Pavel Labath5eb721e2015-05-07 08:30:31 +00003477Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003478NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3479{
3480 load_addr = LLDB_INVALID_ADDRESS;
3481 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3482 [&] (const std::string &line) -> bool
3483 {
3484 StringRef maps_row(line);
3485
3486 SmallVector<StringRef, 16> maps_columns;
3487 maps_row.split(maps_columns, StringRef(" "), -1, false);
3488
3489 if (maps_columns.size() < 6)
3490 {
3491 // Return true to continue reading the proc file
3492 return true;
3493 }
3494
3495 if (maps_columns[5] == file_name)
3496 {
3497 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3498 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3499
3500 // Return false to stop reading the proc file further
3501 return false;
3502 }
3503
3504 // Return true to continue reading the proc file
3505 return true;
3506 });
3507 return error;
3508}
3509
3510Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003511NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003512 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003513 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003514 bool error_when_already_running)
3515{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003516 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003517
3518 if (log)
3519 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3520 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003521
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003522 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3523 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003524
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003525 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003526 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003527 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003528
3529 lldbassert(!(error_when_already_running && !is_stopped));
3530
Pavel Labathc0765592015-05-06 10:46:34 +00003531 if (!is_stopped)
3532 {
3533 // It's not an error, just a log, if the error_when_already_running flag is not set.
3534 // This covers cases where, for instance, we're just trying to resume all threads
3535 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003536 if (log)
3537 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3538 __FUNCTION__,
3539 tid);
3540 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003541 }
3542
3543 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003544 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003545 // this thread to stop. This is potentially a buggy situation since
3546 // we're ostensibly waiting for threads to stop before we send out the
3547 // pending notification, and here we are resuming one before we send
3548 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003549 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003550 {
Pavel Labath108c3252015-05-12 09:03:18 +00003551 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 +00003552 }
3553
3554 // Request a resume. We expect this to be synchronous and the system
3555 // to reflect it is running after this completes.
3556 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003557 if (error.Success())
3558 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003559 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003560 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003561 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003562 __FUNCTION__, tid, error.AsCString ());
3563 }
3564
Pavel Labath5eb721e2015-05-07 08:30:31 +00003565 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003566}
3567
3568//===----------------------------------------------------------------------===//
3569
3570void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003571NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003572{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003573 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003574
Pavel Labath5eb721e2015-05-07 08:30:31 +00003575 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003576 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003577 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003578 __FUNCTION__, triggering_tid);
3579 }
3580
Pavel Labath337f3eb2015-05-08 08:57:45 +00003581 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003582
Pavel Labath5eb721e2015-05-07 08:30:31 +00003583 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003584 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003585 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003586 }
3587}
3588
3589void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003590NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003591{
3592 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3593 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003594 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3595
3596 // Clear any temporary breakpoints we used to implement software single stepping.
3597 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3598 {
3599 Error error = RemoveBreakpoint (thread_info.second);
3600 if (error.Fail())
3601 if (log)
3602 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3603 __FUNCTION__, thread_info.first, error.AsCString());
3604 }
3605 m_threads_stepping_with_breakpoint.clear();
3606
3607 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003608 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3609 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003610 m_pending_notification_up.reset();
3611 }
3612}
3613
Pavel Labathc0765592015-05-06 10:46:34 +00003614void
3615NativeProcessLinux::RequestStopOnAllRunningThreads()
3616{
3617 // Request a stop for all the thread stops that need to be stopped
3618 // and are not already known to be stopped. Keep a list of all the
3619 // threads from which we still need to hear a stop reply.
3620
3621 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003622 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003623 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003624 // We only care about running threads
3625 if (StateIsStoppedState(thread_sp->GetState(), true))
3626 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003627
Pavel Labath108c3252015-05-12 09:03:18 +00003628 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3629 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003630 }
3631
3632 // Set the wait list to the set of tids for which we requested stops.
3633 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3634}
3635
Pavel Labathc0765592015-05-06 10:46:34 +00003636
Pavel Labath5eb721e2015-05-07 08:30:31 +00003637Error
3638NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003639{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003640 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3641
3642 if (log)
3643 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3644 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3645
Pavel Labathc0765592015-05-06 10:46:34 +00003646 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003647 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3648 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003649
3650 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003651 auto& context = thread_sp->GetThreadContext();
3652 const auto stop_was_requested = context.stop_requested;
3653 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003654
3655 // If we have a pending notification, remove this from the set.
3656 if (m_pending_notification_up)
3657 {
3658 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003659 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003660 }
3661
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003662 Error error;
3663 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003664 {
3665 // We can end up here if stop was initiated by LLGS but by this time a
3666 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003667 if (log)
3668 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003669 error = context.request_resume_function (tid, true);
3670 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003671 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003672 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3673 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003674 }
3675 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003676 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003677}
3678
3679void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003680NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003681{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003682 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3683 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003684 {
3685 // Yikes - we've already got a pending signal notification in progress.
3686 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003687 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 +00003688 __FUNCTION__,
3689 m_pending_notification_up->triggering_tid,
3690 notification_up->triggering_tid);
3691 }
3692 m_pending_notification_up = std::move(notification_up);
3693
Pavel Labath108c3252015-05-12 09:03:18 +00003694 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003695
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003696 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003697}
3698
3699void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003700NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003701{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003702 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3703
3704 if (log)
3705 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3706
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003707 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3708 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003709
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003710 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003711 {
3712 // We will need to wait for this new thread to stop as well before firing the
3713 // notification.
3714 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003715 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003716 }
3717}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003718
3719Error
Pavel Labathc7512fd2015-06-26 10:14:12 +00003720NativeProcessLinux::DoOperation(const Operation &op)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003721{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003722 return m_monitor_up->DoOperation(op);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003723}
3724
3725// Wrapper for ptrace to catch errors and log calls.
3726// 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 +00003727Error
3728NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003729{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003730 Error error;
3731 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003732
3733 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3734
3735 PtraceDisplayBytes(req, data, data_size);
3736
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003737 errno = 0;
3738 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003739 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003740 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003741 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003742
Pavel Labath4a9babb2015-06-30 17:04:49 +00003743 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003744 error.SetErrorToErrno();
3745
Pavel Labath4a9babb2015-06-30 17:04:49 +00003746 if (result)
3747 *result = ret;
3748
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003749 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003750 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003751
3752 PtraceDisplayBytes(req, data, data_size);
3753
3754 if (log && error.GetError() != 0)
3755 {
3756 const char* str;
3757 switch (error.GetError())
3758 {
3759 case ESRCH: str = "ESRCH"; break;
3760 case EINVAL: str = "EINVAL"; break;
3761 case EBUSY: str = "EBUSY"; break;
3762 case EPERM: str = "EPERM"; break;
3763 default: str = error.AsCString();
3764 }
3765 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3766 }
3767
Pavel Labath4a9babb2015-06-30 17:04:49 +00003768 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003769}