blob: 372ac789d6aa1a0048955ad8e3822cbed850fb2f [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 "NativeThreadLinux.h"
47#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000048#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000049
Tamas Berghammerd8584872015-02-06 10:57:40 +000050// System includes - They have to be included after framework includes because they define some
51// macros which collide with variable names in other modules
52#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000053#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000054
Pavel Labathdf7c6992015-06-17 18:38:49 +000055#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000056#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/user.h>
58#include <sys/wait.h>
59
Vince Harron8b335672015-05-12 01:10:56 +000060#include "lldb/Host/linux/Personality.h"
61#include "lldb/Host/linux/Ptrace.h"
62#include "lldb/Host/linux/Signalfd.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000063#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000064#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000065
Todd Fiala0bce1b62014-08-17 00:10:50 +000066#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000067
68// Support hardware breakpoints in case it has not been defined
69#ifndef TRAP_HWBKPT
70 #define TRAP_HWBKPT 4
71#endif
72
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000073using namespace lldb;
74using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000075using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000076using namespace llvm;
77
Todd Fialaaf245d12014-06-30 21:05:18 +000078// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000079
80static bool ProcessVmReadvSupported()
81{
82 static bool is_supported;
83 static std::once_flag flag;
84
85 std::call_once(flag, [] {
86 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
87
88 uint32_t source = 0x47424742;
89 uint32_t dest = 0;
90
91 struct iovec local, remote;
92 remote.iov_base = &source;
93 local.iov_base = &dest;
94 remote.iov_len = local.iov_len = sizeof source;
95
96 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
97 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
98 is_supported = (res == sizeof(source) && source == dest);
99 if (log)
100 {
101 if (is_supported)
102 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
103 __FUNCTION__);
104 else
105 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
106 __FUNCTION__, strerror(errno));
107 }
108 });
109
110 return is_supported;
111}
112
Todd Fialaaf245d12014-06-30 21:05:18 +0000113namespace
114{
Todd Fialaaf245d12014-06-30 21:05:18 +0000115 Error
116 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
117 {
118 // Grab process info for the running process.
119 ProcessInstanceInfo process_info;
120 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000121 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000122
123 // Resolve the executable module.
124 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000125 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000126 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
127 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000128 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000129 exe_module_sp,
130 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
131
132 if (!error.Success ())
133 return error;
134
135 // Check if we've got our architecture from the exe_module.
136 arch = exe_module_sp->GetArchitecture ();
137 if (arch.IsValid ())
138 return Error();
139 else
140 return Error("failed to retrieve a valid architecture from the exe module");
141 }
142
143 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000144 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000145 {
146 uint8_t *ptr = (uint8_t *)bytes;
147 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
148 for(uint32_t i=0; i<loop_count; i++)
149 {
150 s.Printf ("[%x]", *ptr);
151 ptr++;
152 }
153 }
154
155 void
156 PtraceDisplayBytes(int &req, void *data, size_t data_size)
157 {
158 StreamString buf;
159 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
160 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
161
162 if (verbose_log)
163 {
164 switch(req)
165 {
166 case PTRACE_POKETEXT:
167 {
168 DisplayBytes(buf, &data, 8);
169 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
170 break;
171 }
172 case PTRACE_POKEDATA:
173 {
174 DisplayBytes(buf, &data, 8);
175 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
176 break;
177 }
178 case PTRACE_POKEUSER:
179 {
180 DisplayBytes(buf, &data, 8);
181 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
182 break;
183 }
184 case PTRACE_SETREGS:
185 {
186 DisplayBytes(buf, data, data_size);
187 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
188 break;
189 }
190 case PTRACE_SETFPREGS:
191 {
192 DisplayBytes(buf, data, data_size);
193 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
194 break;
195 }
196 case PTRACE_SETSIGINFO:
197 {
198 DisplayBytes(buf, data, sizeof(siginfo_t));
199 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
200 break;
201 }
202 case PTRACE_SETREGSET:
203 {
204 // Extract iov_base from data, which is a pointer to the struct IOVEC
205 DisplayBytes(buf, *(void **)data, data_size);
206 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
207 break;
208 }
209 default:
210 {
211 }
212 }
213 }
214 }
215
Todd Fialaaf245d12014-06-30 21:05:18 +0000216 //------------------------------------------------------------------------------
217 // Static implementations of NativeProcessLinux::ReadMemory and
218 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
219 // functions without needed to go thru the thread funnel.
220
Pavel Labathc7512fd2015-06-26 10:14:12 +0000221 Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000222 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000223 lldb::pid_t pid,
224 lldb::addr_t vm_addr,
225 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000226 size_t size,
Pavel Labathc7512fd2015-06-26 10:14:12 +0000227 size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +0000228 {
229 // ptrace word size is determined by the host, not the child
230 static const unsigned word_size = sizeof(void*);
231 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000232 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000233 long data;
234
235 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
236 if (log)
237 ProcessPOSIXLog::IncNestLevel();
238 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
239 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
240 pid, word_size, (void*)vm_addr, buf, size);
241
242 assert(sizeof(data) >= word_size);
243 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
244 {
Pavel Labath4a9babb2015-06-30 17:04:49 +0000245 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, &data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000246 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000247 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000248 if (log)
249 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000250 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000251 }
252
253 remainder = size - bytes_read;
254 remainder = remainder > word_size ? word_size : remainder;
255
256 // Copy the data into our buffer
257 for (unsigned i = 0; i < remainder; ++i)
258 dst[i] = ((data >> i*8) & 0xFF);
259
260 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
261 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
262 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
263 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
264 {
265 uintptr_t print_dst = 0;
266 // Format bytes from data by moving into print_dst for log output
267 for (unsigned i = 0; i < remainder; ++i)
268 print_dst |= (((data >> i*8) & 0xFF) << i*8);
269 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
270 (void*)vm_addr, print_dst, (unsigned long)data);
271 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000272 vm_addr += word_size;
273 dst += word_size;
274 }
275
276 if (log)
277 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000278 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +0000279 }
280
Pavel Labathc7512fd2015-06-26 10:14:12 +0000281 Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000282 DoWriteMemory(
283 lldb::pid_t pid,
284 lldb::addr_t vm_addr,
285 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000286 size_t size,
Pavel Labathc7512fd2015-06-26 10:14:12 +0000287 size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +0000288 {
289 // ptrace word size is determined by the host, not the child
290 static const unsigned word_size = sizeof(void*);
291 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000292 size_t remainder;
Pavel Labathc7512fd2015-06-26 10:14:12 +0000293 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000294
295 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
296 if (log)
297 ProcessPOSIXLog::IncNestLevel();
298 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
299 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
300 pid, word_size, (void*)vm_addr, buf, size);
301
302 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
303 {
304 remainder = size - bytes_written;
305 remainder = remainder > word_size ? word_size : remainder;
306
307 if (remainder == word_size)
308 {
309 unsigned long data = 0;
310 assert(sizeof(data) >= word_size);
311 for (unsigned i = 0; i < word_size; ++i)
312 data |= (unsigned long)src[i] << i*8;
313
314 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
315 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
316 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
317 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
318 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000319 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000320
Pavel Labath4a9babb2015-06-30 17:04:49 +0000321 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data);
322 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000323 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000324 if (log)
325 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000326 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000327 }
328 }
329 else
330 {
331 unsigned char buff[8];
Pavel Labathc7512fd2015-06-26 10:14:12 +0000332 size_t bytes_read;
333 error = DoReadMemory(pid, vm_addr, buff, word_size, bytes_read);
334 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000335 {
336 if (log)
337 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000338 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000339 }
340
341 memcpy(buff, src, remainder);
342
Pavel Labathc7512fd2015-06-26 10:14:12 +0000343 size_t bytes_written_rec;
344 error = DoWriteMemory(pid, vm_addr, buff, word_size, bytes_written_rec);
345 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000346 {
347 if (log)
348 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000349 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000350 }
351
352 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
353 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
354 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
355 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
356 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000357 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000358 }
359
360 vm_addr += word_size;
361 src += word_size;
362 }
363 if (log)
364 ProcessPOSIXLog::DecNestLevel();
Pavel Labathc7512fd2015-06-26 10:14:12 +0000365 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000366 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000367} // end of anonymous namespace
368
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000369// Simple helper function to ensure flags are enabled on the given file
370// descriptor.
371static Error
372EnsureFDFlags(int fd, int flags)
373{
374 Error error;
375
376 int status = fcntl(fd, F_GETFL);
377 if (status == -1)
378 {
379 error.SetErrorToErrno();
380 return error;
381 }
382
383 if (fcntl(fd, F_SETFL, status | flags) == -1)
384 {
385 error.SetErrorToErrno();
386 return error;
387 }
388
389 return error;
390}
391
392// This class encapsulates the privileged thread which performs all ptrace and wait operations on
393// the inferior. The thread consists of a main loop which waits for events and processes them
394// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
395// the inferior process. Upon receiving this signal we do a waitpid to get more information
396// and dispatch to NativeProcessLinux::MonitorCallback.
397// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
398// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
399// pipe, and the completion of the operation is signalled over the semaphore.
400// - thread exit event: this is signaled from the Monitor destructor by closing the write end
401// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000402class NativeProcessLinux::Monitor
403{
Pavel Labath1107b5a2015-04-17 14:07:49 +0000404private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000405 // The initial monitor operation (launch or attach). It returns a inferior process id.
406 std::unique_ptr<InitialOperation> m_initial_operation_up;
407
408 ::pid_t m_child_pid = -1;
409 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000410
411 enum { READ, WRITE };
412 int m_pipefd[2] = {-1, -1};
413 int m_signal_fd = -1;
414 HostThread m_thread;
415
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000416 // current operation which must be executed on the priviliged thread
Pavel Labathc7512fd2015-06-26 10:14:12 +0000417 Mutex m_operation_mutex;
418 const Operation *m_operation = nullptr;
419 sem_t m_operation_sem;
420 Error m_operation_error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000421
Pavel Labath45f5cb32015-05-05 15:05:50 +0000422 unsigned m_operation_nesting_level = 0;
423
424 static constexpr char operation_command = 'o';
425 static constexpr char begin_block_command = '{';
426 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000427
Pavel Labath1107b5a2015-04-17 14:07:49 +0000428 void
429 HandleSignals();
430
431 void
432 HandleWait();
433
434 // Returns true if the thread should exit.
435 bool
436 HandleCommands();
437
438 void
439 MainLoop();
440
441 static void *
442 RunMonitor(void *arg);
443
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000444 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000445 WaitForAck();
446
447 void
448 BeginOperationBlock()
449 {
450 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
451 WaitForAck();
452 }
453
454 void
455 EndOperationBlock()
456 {
457 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
458 WaitForAck();
459 }
460
Pavel Labath1107b5a2015-04-17 14:07:49 +0000461public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000462 Monitor(const InitialOperation &initial_operation,
463 NativeProcessLinux *native_process)
464 : m_initial_operation_up(new InitialOperation(initial_operation)),
465 m_native_process(native_process)
466 {
467 sem_init(&m_operation_sem, 0, 0);
468 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000469
470 ~Monitor();
471
472 Error
473 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000474
475 void
Pavel Labath45f5cb32015-05-05 15:05:50 +0000476 Terminate();
477
Pavel Labathc7512fd2015-06-26 10:14:12 +0000478 Error
479 DoOperation(const Operation &op);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000480
481 class ScopedOperationLock {
482 Monitor &m_monitor;
483
484 public:
485 ScopedOperationLock(Monitor &monitor)
486 : m_monitor(monitor)
487 { m_monitor.BeginOperationBlock(); }
488
489 ~ScopedOperationLock()
490 { m_monitor.EndOperationBlock(); }
491 };
Pavel Labath1107b5a2015-04-17 14:07:49 +0000492};
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000493constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +0000494constexpr char NativeProcessLinux::Monitor::begin_block_command;
495constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000496
497Error
498NativeProcessLinux::Monitor::Initialize()
499{
500 Error error;
501
502 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
503 // listening for these signals over a signalfd file descriptors. This allows us to wait for
504 // multiple kinds of events with select.
505 sigset_t signals;
506 sigemptyset(&signals);
507 sigaddset(&signals, SIGCHLD);
508 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
509 if (m_signal_fd < 0)
510 {
511 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
512 __FUNCTION__, strerror(errno));
513
514 }
515
516 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
517 {
518 error.SetErrorToErrno();
519 return error;
520 }
521
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000522 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
523 return error;
524 }
525
526 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
527 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000528 if (!m_thread.IsJoinable())
529 return Error("Failed to create monitor thread for NativeProcessLinux.");
530
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000531 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000532 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000533}
534
Pavel Labathc7512fd2015-06-26 10:14:12 +0000535Error
536NativeProcessLinux::Monitor::DoOperation(const Operation &op)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000537{
538 if (m_thread.EqualsThread(pthread_self())) {
539 // If we're on the Monitor thread, we can simply execute the operation.
Pavel Labathc7512fd2015-06-26 10:14:12 +0000540 return op();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000541 }
542
543 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
544 Mutex::Locker lock(m_operation_mutex);
545
Pavel Labathc7512fd2015-06-26 10:14:12 +0000546 m_operation = &op;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000547
548 // notify the thread that an operation is ready to be processed
549 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
550
Pavel Labathc7512fd2015-06-26 10:14:12 +0000551 return WaitForAck();
Pavel Labath45f5cb32015-05-05 15:05:50 +0000552}
553
554void
555NativeProcessLinux::Monitor::Terminate()
556{
557 if (m_pipefd[WRITE] >= 0)
558 {
559 close(m_pipefd[WRITE]);
560 m_pipefd[WRITE] = -1;
561 }
562 if (m_thread.IsJoinable())
563 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +0000564}
565
Pavel Labath1107b5a2015-04-17 14:07:49 +0000566NativeProcessLinux::Monitor::~Monitor()
567{
Pavel Labath45f5cb32015-05-05 15:05:50 +0000568 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +0000569 if (m_pipefd[READ] >= 0)
570 close(m_pipefd[READ]);
571 if (m_signal_fd >= 0)
572 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000573 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000574}
575
576void
577NativeProcessLinux::Monitor::HandleSignals()
578{
579 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
580
581 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
582 // all the information from waitpid(). We just need to read all the signals so that we can
583 // sleep next time we reach select().
584 while (true)
585 {
586 signalfd_siginfo info;
587 ssize_t size = read(m_signal_fd, &info, sizeof info);
588 if (size == -1)
589 {
590 if (errno == EAGAIN || errno == EWOULDBLOCK)
591 break; // We are done.
592 if (errno == EINTR)
593 continue;
594 if (log)
595 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
596 __FUNCTION__, strerror(errno));
597 break;
598 }
599 if (size != sizeof info)
600 {
601 // We got incomplete information structure. This should not happen, let's just log
602 // that.
603 if (log)
604 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
605 "structure size is %zd, read returned %zd bytes",
606 __FUNCTION__, sizeof info, size);
607 break;
608 }
609 if (log)
610 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
611 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
612 }
613}
614
615void
616NativeProcessLinux::Monitor::HandleWait()
617{
618 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
619 // Process all pending waitpid notifications.
620 while (true)
621 {
622 int status = -1;
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000623 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000624
625 if (wait_pid == 0)
626 break; // We are done.
627
628 if (wait_pid == -1)
629 {
630 if (errno == EINTR)
631 continue;
632
633 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000634 log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
635 __FUNCTION__, strerror(errno));
Pavel Labath1107b5a2015-04-17 14:07:49 +0000636 break;
637 }
638
639 bool exited = false;
640 int signal = 0;
641 int exit_status = 0;
642 const char *status_cstr = NULL;
643 if (WIFSTOPPED(status))
644 {
645 signal = WSTOPSIG(status);
646 status_cstr = "STOPPED";
647 }
648 else if (WIFEXITED(status))
649 {
650 exit_status = WEXITSTATUS(status);
651 status_cstr = "EXITED";
652 exited = true;
653 }
654 else if (WIFSIGNALED(status))
655 {
656 signal = WTERMSIG(status);
657 status_cstr = "SIGNALED";
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000658 if (wait_pid == m_child_pid) {
Pavel Labath1107b5a2015-04-17 14:07:49 +0000659 exited = true;
660 exit_status = -1;
661 }
662 }
663 else
664 status_cstr = "(\?\?\?)";
665
666 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000667 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
Pavel Labath1107b5a2015-04-17 14:07:49 +0000668 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000669 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000670
671 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
672 }
673}
674
675bool
676NativeProcessLinux::Monitor::HandleCommands()
677{
678 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
679
680 while (true)
681 {
682 char command = 0;
683 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
684 if (size == -1)
685 {
686 if (errno == EAGAIN || errno == EWOULDBLOCK)
687 return false;
688 if (errno == EINTR)
689 continue;
690 if (log)
691 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
692 return true;
693 }
694 if (size == 0) // end of file - write end closed
695 {
696 if (log)
697 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000698 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000699 return true; // We are done.
700 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000701
702 switch (command)
703 {
704 case operation_command:
Pavel Labathc7512fd2015-06-26 10:14:12 +0000705 m_operation_error = (*m_operation)();
Pavel Labath45f5cb32015-05-05 15:05:50 +0000706 break;
707 case begin_block_command:
708 ++m_operation_nesting_level;
709 break;
710 case end_block_command:
711 assert(m_operation_nesting_level > 0);
712 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000713 break;
714 default:
715 if (log)
716 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
717 __FUNCTION__, command);
718 }
Pavel Labath45f5cb32015-05-05 15:05:50 +0000719
720 // notify calling thread that the command has been processed
721 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000722 }
723}
724
725void
726NativeProcessLinux::Monitor::MainLoop()
727{
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000728 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
729 m_initial_operation_up.reset();
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000730 m_child_pid = child_pid;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000731 sem_post(&m_operation_sem);
732
Pavel Labath1107b5a2015-04-17 14:07:49 +0000733 while (true)
734 {
735 fd_set fds;
736 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000737 // Only process waitpid events if we are outside of an operation block. Any pending
738 // events will be processed after we leave the block.
739 if (m_operation_nesting_level == 0)
740 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000741 FD_SET(m_pipefd[READ], &fds);
742
743 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
744 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
745 if (r < 0)
746 {
747 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
748 if (log)
749 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
750 __FUNCTION__, strerror(errno));
751 return;
752 }
753
754 if (FD_ISSET(m_pipefd[READ], &fds))
755 {
756 if (HandleCommands())
757 return;
758 }
759
760 if (FD_ISSET(m_signal_fd, &fds))
761 {
762 HandleSignals();
763 HandleWait();
764 }
765 }
766}
767
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000768Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000769NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000770{
771 Error error;
772 while (sem_wait(&m_operation_sem) != 0)
773 {
774 if (errno == EINTR)
775 continue;
776
777 error.SetErrorToErrno();
778 return error;
779 }
780
781 return m_operation_error;
782}
783
Pavel Labath1107b5a2015-04-17 14:07:49 +0000784void *
785NativeProcessLinux::Monitor::RunMonitor(void *arg)
786{
787 static_cast<Monitor *>(arg)->MainLoop();
788 return nullptr;
789}
790
791
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000792NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000793 char const **argv,
794 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000795 const FileSpec &stdin_file_spec,
796 const FileSpec &stdout_file_spec,
797 const FileSpec &stderr_file_spec,
798 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000799 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000800 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000801 m_argv(argv),
802 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000803 m_stdin_file_spec(stdin_file_spec),
804 m_stdout_file_spec(stdout_file_spec),
805 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000806 m_working_dir(working_dir),
807 m_launch_info(launch_info)
808{
809}
Todd Fialaaf245d12014-06-30 21:05:18 +0000810
811NativeProcessLinux::LaunchArgs::~LaunchArgs()
812{ }
813
Todd Fialaaf245d12014-06-30 21:05:18 +0000814// -----------------------------------------------------------------------------
815// Public Static Methods
816// -----------------------------------------------------------------------------
817
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000818Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000819NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000820 ProcessLaunchInfo &launch_info,
821 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000822 NativeProcessProtocolSP &native_process_sp)
823{
824 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
825
Pavel Labathd5b310f2015-07-09 11:51:11 +0000826 lldb::ModuleSP exe_module_sp;
827 PlatformSP platform_sp (Platform::GetHostPlatform ());
828 Error error = platform_sp->ResolveExecutable(
829 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
830 exe_module_sp,
831 nullptr);
832
833 if (! error.Success())
834 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000835
836 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000837 FileSpec working_dir{launch_info.GetWorkingDirectory()};
838 if (working_dir &&
839 (!working_dir.ResolvePath() ||
840 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000841 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000842 error.SetErrorStringWithFormat ("No such file or directory: %s",
843 working_dir.GetCString());
844 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000845 }
846
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000847 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000848
Chaoren Lind3173f32015-05-29 19:52:29 +0000849 // Default of empty will mean to use existing open file descriptors.
850 FileSpec stdin_file_spec{};
851 FileSpec stdout_file_spec{};
852 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000853
854 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000855 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000856 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000857
858 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000859 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000860 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000861
862 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000863 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000864 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000865
866 if (log)
867 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000868 if (stdin_file_spec)
869 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
870 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000871 else
872 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
873
Chaoren Lind3173f32015-05-29 19:52:29 +0000874 if (stdout_file_spec)
875 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
876 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000877 else
878 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
879
Chaoren Lind3173f32015-05-29 19:52:29 +0000880 if (stderr_file_spec)
881 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
882 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000883 else
884 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
885 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000886
887 // Create the NativeProcessLinux in launch mode.
888 native_process_sp.reset (new NativeProcessLinux ());
889
890 if (log)
891 {
892 int i = 0;
893 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
894 {
895 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
896 ++i;
897 }
898 }
899
900 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
901 {
902 native_process_sp.reset ();
903 error.SetErrorStringWithFormat ("failed to register the native delegate");
904 return error;
905 }
906
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000907 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labathd5b310f2015-07-09 11:51:11 +0000908 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000909 launch_info.GetArguments ().GetConstArgumentVector (),
910 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000911 stdin_file_spec,
912 stdout_file_spec,
913 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000914 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000915 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000916 error);
917
918 if (error.Fail ())
919 {
920 native_process_sp.reset ();
921 if (log)
922 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
923 return error;
924 }
925
926 launch_info.SetProcessID (native_process_sp->GetID ());
927
928 return error;
929}
930
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000931Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000932NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000933 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000934 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000935 NativeProcessProtocolSP &native_process_sp)
936{
937 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
938 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
939 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
940
941 // Grab the current platform architecture. This should be Linux,
942 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000943 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000944 if (!platform_sp)
945 return Error("failed to get a valid default platform");
946
947 // Retrieve the architecture for the running process.
948 ArchSpec process_arch;
949 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
950 if (!error.Success ())
951 return error;
952
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000953 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000954
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000955 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000956 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000957 error.SetErrorStringWithFormat ("failed to register the native delegate");
958 return error;
959 }
960
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000961 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000962 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000964
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000965 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000966 return error;
967}
968
969// -----------------------------------------------------------------------------
970// Public Instance Methods
971// -----------------------------------------------------------------------------
972
973NativeProcessLinux::NativeProcessLinux () :
974 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
975 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000976 m_supports_mem_region (eLazyBoolCalculate),
977 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +0000978 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000979{
980}
981
982//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000983// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
984// Refer to Monitor and Operation classes to see why this is necessary.
985//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000986void
987NativeProcessLinux::LaunchInferior (
988 Module *module,
989 const char *argv[],
990 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000991 const FileSpec &stdin_file_spec,
992 const FileSpec &stdout_file_spec,
993 const FileSpec &stderr_file_spec,
994 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000995 const ProcessLaunchInfo &launch_info,
996 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000997{
998 if (module)
999 m_arch = module->GetArchitecture ();
1000
Chaoren Linfa03ad22015-02-03 01:50:42 +00001001 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001002
1003 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +00001004 new LaunchArgs(module, argv, envp,
1005 stdin_file_spec,
1006 stdout_file_spec,
1007 stderr_file_spec,
1008 working_dir,
1009 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001010
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001011 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001012 if (!error.Success ())
1013 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001014}
1015
1016void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001017NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001018{
1019 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1020 if (log)
1021 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1022
1023 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001024 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001025 if (!platform_sp)
1026 {
1027 if (log)
1028 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1029 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001030 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001031 }
1032
1033 // Gather info about the process.
1034 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001035 if (!platform_sp->GetProcessInfo (pid, process_info))
1036 {
1037 if (log)
1038 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1039 error.SetErrorString ("failed to get process info");
1040 return;
1041 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001042
1043 // Resolve the executable module
1044 ModuleSP exe_module_sp;
1045 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001046 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001047 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001048 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001049 if (!error.Success())
1050 return;
1051
1052 // Set the architecture to the exe architecture.
1053 m_arch = exe_module_sp->GetArchitecture();
1054 if (log)
1055 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1056
1057 m_pid = pid;
1058 SetState(eStateAttaching);
1059
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001060 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001061 if (!error.Success ())
1062 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001063}
1064
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001065void
1066NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001067{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001068 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001069}
1070
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001071::pid_t
1072NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001073{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001074 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001075
1076 const char **argv = args->m_argv;
1077 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +00001078 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +00001079
1080 lldb_utility::PseudoTerminal terminal;
1081 const size_t err_len = 1024;
1082 char err_str[err_len];
1083 lldb::pid_t pid;
1084 NativeThreadProtocolSP thread_sp;
1085
1086 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001087
1088 // Propagate the environment if one is not supplied.
1089 if (envp == NULL || envp[0] == NULL)
1090 envp = const_cast<const char **>(environ);
1091
1092 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1093 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001094 error.SetErrorToGenericError();
1095 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1096 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001097 }
1098
1099 // Recognized child exit status codes.
1100 enum {
1101 ePtraceFailed = 1,
1102 eDupStdinFailed,
1103 eDupStdoutFailed,
1104 eDupStderrFailed,
1105 eChdirFailed,
1106 eExecFailed,
1107 eSetGidFailed
1108 };
1109
1110 // Child process.
1111 if (pid == 0)
1112 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001113 // FIXME consider opening a pipe between parent/child and have this forked child
1114 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001115
Todd Fiala75f47c32014-10-11 21:42:09 +00001116 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001117 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001118 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001119 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001120
Pavel Labath493c3a12015-02-04 10:36:57 +00001121 // terminal has already dupped the tty descriptors to stdin/out/err.
1122 // This closes original fd from which they were copied (and avoids
1123 // leaking descriptors to the debugged process.
1124 terminal.CloseSlaveFileDescriptor();
1125
Todd Fialaaf245d12014-06-30 21:05:18 +00001126 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001127 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001128 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001129
1130 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001131 if (setpgid(0, 0) != 0)
1132 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001133 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001134 // Don't allow this to prevent an inferior exec.
1135 }
1136
1137 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +00001138 if (args->m_stdin_file_spec)
1139 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001140 exit(eDupStdinFailed);
1141
Chaoren Lind3173f32015-05-29 19:52:29 +00001142 if (args->m_stdout_file_spec)
1143 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001144 exit(eDupStdoutFailed);
1145
Chaoren Lind3173f32015-05-29 19:52:29 +00001146 if (args->m_stderr_file_spec)
1147 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001148 exit(eDupStderrFailed);
1149
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001150 // Close everything besides stdin, stdout, and stderr that has no file
1151 // action to avoid leaking
1152 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1153 if (!args->m_launch_info.GetFileActionForFD(fd))
1154 close(fd);
1155
Todd Fialaaf245d12014-06-30 21:05:18 +00001156 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +00001157 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +00001158 exit(eChdirFailed);
1159
Todd Fiala0bce1b62014-08-17 00:10:50 +00001160 // Disable ASLR if requested.
1161 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1162 {
1163 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1164 if (old_personality == -1)
1165 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001166 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001167 }
1168 else
1169 {
1170 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1171 if (new_personality == -1)
1172 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001173 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001174 }
1175 else
1176 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001177 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001178 }
1179 }
1180 }
1181
Todd Fiala75f47c32014-10-11 21:42:09 +00001182 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001183 execve(argv[0],
1184 const_cast<char *const *>(argv),
1185 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001186
1187 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001188 exit(eExecFailed);
1189 }
1190
Todd Fiala75f47c32014-10-11 21:42:09 +00001191 //
1192 // This is the parent code here.
1193 //
1194 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1195
Todd Fialaaf245d12014-06-30 21:05:18 +00001196 // Wait for the child process to trap on its call to execve.
1197 ::pid_t wpid;
1198 int status;
1199 if ((wpid = waitpid(pid, &status, 0)) < 0)
1200 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001201 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001202 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001203 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1204 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001205
1206 // Mark the inferior as invalid.
1207 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001208 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001209
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001210 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001211 }
1212 else if (WIFEXITED(status))
1213 {
1214 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001215 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001216 switch (WEXITSTATUS(status))
1217 {
1218 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001219 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001220 break;
1221 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001222 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001223 break;
1224 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001225 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001226 break;
1227 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001228 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001229 break;
1230 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001231 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 break;
1233 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001234 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001235 break;
1236 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001237 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001238 break;
1239 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001240 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 break;
1242 }
1243
1244 if (log)
1245 {
1246 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1247 __FUNCTION__,
1248 WEXITSTATUS(status));
1249 }
1250
1251 // Mark the inferior as invalid.
1252 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001253 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001254
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001255 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001256 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001257 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001258 "Could not sync with inferior process.");
1259
1260 if (log)
1261 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1262
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001263 error = SetDefaultPtraceOpts(pid);
1264 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001265 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001266 if (log)
1267 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001268 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001269
1270 // Mark the inferior as invalid.
1271 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001272 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001273
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001274 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001275 }
1276
1277 // Release the master terminal descriptor and pass it off to the
1278 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001279 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1280 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001281
1282 // Set the terminal fd to be in non blocking mode (it simplifies the
1283 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1284 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001285 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1286 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001287 {
1288 if (log)
1289 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001290 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001291
1292 // Mark the inferior as invalid.
1293 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001294 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001295
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001296 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001297 }
1298
1299 if (log)
1300 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1301
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001302 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001303 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001304 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001305 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001306
1307 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001308 SetCurrentThreadID (thread_sp->GetID ());
1309 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001310
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 if (log)
1312 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001313 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001314 {
1315 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1316 }
1317 else
1318 {
1319 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001320 __FUNCTION__, error.AsCString ());
1321 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001322 }
1323 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001324 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001325}
1326
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001327::pid_t
1328NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001329{
Todd Fialaaf245d12014-06-30 21:05:18 +00001330 lldb::ThreadSP inferior;
1331 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1332
1333 // Use a map to keep track of the threads which we have attached/need to attach.
1334 Host::TidMap tids_to_attach;
1335 if (pid <= 1)
1336 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001337 error.SetErrorToGenericError();
1338 error.SetErrorString("Attaching to process 1 is not allowed.");
1339 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001340 }
1341
1342 while (Host::FindProcessThreads(pid, tids_to_attach))
1343 {
1344 for (Host::TidMap::iterator it = tids_to_attach.begin();
1345 it != tids_to_attach.end();)
1346 {
1347 if (it->second == false)
1348 {
1349 lldb::tid_t tid = it->first;
1350
1351 // Attach to the requested process.
1352 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001353 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001354 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001355 {
1356 // No such thread. The thread may have exited.
1357 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001358 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001359 {
1360 it = tids_to_attach.erase(it);
1361 continue;
1362 }
1363 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001364 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001365 }
1366
1367 int status;
1368 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1369 // At this point we should have a thread stopped if waitpid succeeds.
1370 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1371 {
1372 // No such thread. The thread may have exited.
1373 // More error handling may be needed.
1374 if (errno == ESRCH)
1375 {
1376 it = tids_to_attach.erase(it);
1377 continue;
1378 }
1379 else
1380 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001381 error.SetErrorToErrno();
1382 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001383 }
1384 }
1385
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001386 error = SetDefaultPtraceOpts(tid);
1387 if (error.Fail())
1388 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001389
1390 if (log)
1391 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1392
1393 it->second = true;
1394
1395 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001396 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001397 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001398
1399 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001400 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001401 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001402 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001403 }
1404
1405 // move the loop forward
1406 ++it;
1407 }
1408 }
1409
1410 if (tids_to_attach.size() > 0)
1411 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001412 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001413 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001414 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001415 }
1416 else
1417 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001418 error.SetErrorToGenericError();
1419 error.SetErrorString("No such process.");
1420 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001421 }
1422
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001423 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001424}
1425
Chaoren Lin97ccc292015-02-03 01:51:12 +00001426Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001427NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1428{
1429 long ptrace_opts = 0;
1430
1431 // Have the child raise an event on exit. This is used to keep the child in
1432 // limbo until it is destroyed.
1433 ptrace_opts |= PTRACE_O_TRACEEXIT;
1434
1435 // Have the tracer trace threads which spawn in the inferior process.
1436 // TODO: if we want to support tracing the inferiors' child, add the
1437 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1438 ptrace_opts |= PTRACE_O_TRACECLONE;
1439
1440 // Have the tracer notify us before execve returns
1441 // (needed to disable legacy SIGTRAP generation)
1442 ptrace_opts |= PTRACE_O_TRACEEXEC;
1443
Pavel Labath4a9babb2015-06-30 17:04:49 +00001444 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +00001445}
1446
1447static ExitType convert_pid_status_to_exit_type (int status)
1448{
1449 if (WIFEXITED (status))
1450 return ExitType::eExitTypeExit;
1451 else if (WIFSIGNALED (status))
1452 return ExitType::eExitTypeSignal;
1453 else if (WIFSTOPPED (status))
1454 return ExitType::eExitTypeStop;
1455 else
1456 {
1457 // We don't know what this is.
1458 return ExitType::eExitTypeInvalid;
1459 }
1460}
1461
1462static int convert_pid_status_to_return_code (int status)
1463{
1464 if (WIFEXITED (status))
1465 return WEXITSTATUS (status);
1466 else if (WIFSIGNALED (status))
1467 return WTERMSIG (status);
1468 else if (WIFSTOPPED (status))
1469 return WSTOPSIG (status);
1470 else
1471 {
1472 // We don't know what this is.
1473 return ExitType::eExitTypeInvalid;
1474 }
1475}
1476
Pavel Labath1107b5a2015-04-17 14:07:49 +00001477// Handles all waitpid events from the inferior process.
1478void
1479NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001480 bool exited,
1481 int signal,
1482 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001483{
1484 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1485
Todd Fialaaf245d12014-06-30 21:05:18 +00001486 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001487 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001488
1489 // Handle when the thread exits.
1490 if (exited)
1491 {
1492 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001493 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 +00001494
1495 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001496 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001497
1498 if (is_main_thread)
1499 {
1500 // We only set the exit status and notify the delegate if we haven't already set the process
1501 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1502 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001503 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001504 if (!already_notified)
1505 {
1506 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001507 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 +00001508 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001509 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001510
1511 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001512 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001513 }
1514 else
1515 {
1516 if (log)
1517 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1518 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001519 }
1520 else
1521 {
1522 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1523 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1524 // and we would have done an all-stop then.
1525 if (log)
1526 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 +00001527 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001528 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001529 }
1530
1531 // Get details on the signal raised.
1532 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001533 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001534 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001535 {
1536 // We have retrieved the signal info. Dispatch appropriately.
1537 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001538 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001539 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001540 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001541 }
1542 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001543 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001544 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001545 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001546 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001547 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1548 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1549 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1550 // generally not needed (one use case is debugging background task being managed by a
1551 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1552 // stop which happens before the group stop. This done by MonitorSignal and works
1553 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001554 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001555 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);
1556 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001557 }
1558 else
1559 {
1560 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1561
1562 // A return value of ESRCH means the thread/process is no longer on the system,
1563 // so it was killed somehow outside of our control. Either way, we can't do anything
1564 // with it anymore.
1565
Todd Fialaaf245d12014-06-30 21:05:18 +00001566 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001567 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001568
1569 if (log)
1570 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001571 __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 +00001572
1573 if (is_main_thread)
1574 {
1575 // Notify the delegate - our process is not available but appears to have been killed outside
1576 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001577 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1578 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001579 }
1580 else
1581 {
1582 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1583 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001584 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 +00001585 }
1586 }
1587 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001588}
1589
1590void
Pavel Labath426bdf82015-04-28 07:51:52 +00001591NativeProcessLinux::WaitForNewThread(::pid_t tid)
1592{
1593 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1594
1595 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1596
1597 if (new_thread_sp)
1598 {
1599 // We are already tracking the thread - we got the event on the new thread (see
1600 // MonitorSignal) before this one. We are done.
1601 return;
1602 }
1603
1604 // The thread is not tracked yet, let's wait for it to appear.
1605 int status = -1;
1606 ::pid_t wait_pid;
1607 do
1608 {
1609 if (log)
1610 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1611 wait_pid = waitpid(tid, &status, __WALL);
1612 }
1613 while (wait_pid == -1 && errno == EINTR);
1614 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1615 // some checks just in case.
1616 if (wait_pid != tid) {
1617 if (log)
1618 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1619 // The only way I know of this could happen is if the whole process was
1620 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1621 return;
1622 }
1623 if (WIFEXITED(status))
1624 {
1625 if (log)
1626 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1627 // Also a very improbable event.
1628 return;
1629 }
1630
1631 siginfo_t info;
1632 Error error = GetSignalInfo(tid, &info);
1633 if (error.Fail())
1634 {
1635 if (log)
1636 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1637 return;
1638 }
1639
1640 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1641 {
1642 // We should be getting a thread creation signal here, but we received something
1643 // else. There isn't much we can do about it now, so we will just log that. Since the
1644 // thread is alive and we are receiving events from it, we shall pretend that it was
1645 // created properly.
1646 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);
1647 }
1648
1649 if (log)
1650 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1651 __FUNCTION__, GetID (), tid);
1652
1653 new_thread_sp = AddThread(tid);
1654 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1655 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001656 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001657}
1658
1659void
Todd Fialaaf245d12014-06-30 21:05:18 +00001660NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1661{
1662 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1663 const bool is_main_thread = (pid == GetID ());
1664
1665 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1666 if (!info)
1667 return;
1668
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001669 Mutex::Locker locker (m_threads_mutex);
1670
Todd Fialaaf245d12014-06-30 21:05:18 +00001671 // See if we can find a thread for this signal.
1672 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1673 if (!thread_sp)
1674 {
1675 if (log)
1676 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1677 }
1678
1679 switch (info->si_code)
1680 {
1681 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1682 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1683 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1684
1685 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1686 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001687 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001688 // creation.
1689 // We don't want to do anything with the parent thread so we just resume it. In case we
1690 // want to implement "break on thread creation" functionality, we would need to stop
1691 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001692
Pavel Labath426bdf82015-04-28 07:51:52 +00001693 unsigned long event_message = 0;
1694 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001695 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001696 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001697 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 +00001698 } else
1699 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001700
Pavel Labath5fd24c62015-04-23 09:04:35 +00001701 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001702 break;
1703 }
1704
1705 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001706 {
1707 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001708 if (log)
1709 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001710
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001711 // Exec clears any pending notifications.
1712 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001713
1714 // 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 +00001715 if (log)
1716 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1717
1718 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001719 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001720 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1721 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001722 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001723 main_thread_sp = thread_sp;
1724 if (log)
1725 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001726 }
1727 else
1728 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001729 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001730 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001731 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001732 }
1733 }
1734
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001735 m_threads.clear ();
1736
1737 if (main_thread_sp)
1738 {
1739 m_threads.push_back (main_thread_sp);
1740 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001741 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001742 }
1743 else
1744 {
1745 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1746 if (log)
1747 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1748 }
1749
Chaoren Linfa03ad22015-02-03 01:50:42 +00001750 // Tell coordinator about about the "new" (since exec) stopped main thread.
1751 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001752 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001753
1754 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1755 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001756 // Let our delegate know we have just exec'd.
1757 NotifyDidExec ();
1758
1759 // If we have a main thread, indicate we are stopped.
1760 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001761
1762 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001763 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001764
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001766 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001767
1768 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1769 {
1770 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001771 // We don't want to do anything with the thread so we just resume it. In case we
1772 // want to implement "break on thread exit" functionality, we would need to stop
1773 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001774
Todd Fialaaf245d12014-06-30 21:05:18 +00001775 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001776 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001777 data = -1;
1778
1779 if (log)
1780 {
1781 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1782 __FUNCTION__,
1783 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1784 pid,
1785 is_main_thread ? "is main thread" : "not main thread");
1786 }
1787
Todd Fialaaf245d12014-06-30 21:05:18 +00001788 if (is_main_thread)
1789 {
1790 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001791 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001792
Pavel Labath6e351632015-05-15 13:30:59 +00001793 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001794
1795 break;
1796 }
1797
1798 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001799 case TRAP_TRACE: // We receive this on single stepping.
1800 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001801 if (thread_sp)
1802 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001803 // If a watchpoint was hit, report it
1804 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001805 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001806 if (error.Fail() && log)
1807 log->Printf("NativeProcessLinux::%s() "
1808 "received error while checking for watchpoint hits, "
1809 "pid = %" PRIu64 " error = %s",
1810 __FUNCTION__, pid, error.AsCString());
1811 if (wp_index != LLDB_INVALID_INDEX32)
1812 {
1813 MonitorWatchpoint(pid, thread_sp, wp_index);
1814 break;
1815 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001816 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001817 // Otherwise, report step over
1818 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001819 break;
1820
1821 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001822#if defined __mips__
1823 // For mips there is no special signal for watchpoint
1824 // So we check for watchpoint in kernel trap
1825 if (thread_sp)
1826 {
1827 // If a watchpoint was hit, report it
1828 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001829 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001830 if (error.Fail() && log)
1831 log->Printf("NativeProcessLinux::%s() "
1832 "received error while checking for watchpoint hits, "
1833 "pid = %" PRIu64 " error = %s",
1834 __FUNCTION__, pid, error.AsCString());
1835 if (wp_index != LLDB_INVALID_INDEX32)
1836 {
1837 MonitorWatchpoint(pid, thread_sp, wp_index);
1838 break;
1839 }
1840 }
1841 // NO BREAK
1842#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001843 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001844 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001845 break;
1846
1847 case SIGTRAP:
1848 case (SIGTRAP | 0x80):
1849 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001850 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1851
Todd Fialaaf245d12014-06-30 21:05:18 +00001852 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001853 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001854 break;
1855
1856 default:
1857 assert(false && "Unexpected SIGTRAP code!");
1858 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001859 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1860 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001861 break;
1862
1863 }
1864}
1865
1866void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001867NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1868{
1869 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1870 if (log)
1871 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1872 __FUNCTION__, pid);
1873
1874 if (thread_sp)
1875 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1876
1877 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001878 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001879
1880 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1881 // This would have already happened at the time the Resume() with step operation was signaled.
1882 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1883 // once all running threads have checked in as stopped.
1884 SetCurrentThreadID(pid);
1885 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001886 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001887}
1888
1889void
1890NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1891{
1892 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1893 if (log)
1894 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1895 __FUNCTION__, pid);
1896
1897 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001898 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001899
1900 // Mark the thread as stopped at breakpoint.
1901 if (thread_sp)
1902 {
1903 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1904 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1905 if (error.Fail())
1906 if (log)
1907 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1908 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001909
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001910 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001911 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001912 }
1913 else
1914 if (log)
1915 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1916 "warning, cannot process software breakpoint since no thread metadata",
1917 __FUNCTION__, pid);
1918
1919
1920 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001921 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001922}
1923
1924void
1925NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1926{
1927 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1928 if (log)
1929 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1930 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1931 __FUNCTION__, pid, wp_index);
1932
1933 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001934 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001935
1936 // Mark the thread as stopped at watchpoint.
1937 // The address is at (lldb::addr_t)info->si_addr if we need it.
1938 lldbassert(thread_sp && "thread_sp cannot be NULL");
1939 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1940
1941 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001942 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001943}
1944
1945void
Todd Fialaaf245d12014-06-30 21:05:18 +00001946NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1947{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001948 assert (info && "null info");
1949 if (!info)
1950 return;
1951
1952 const int signo = info->si_signo;
1953 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001954
1955 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1956
1957 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1958 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1959 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1960 //
1961 // IOW, user generated signals never generate what we consider to be a
1962 // "crash".
1963 //
1964 // Similarly, ACK signals generated by this monitor.
1965
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001966 Mutex::Locker locker (m_threads_mutex);
1967
Todd Fialaaf245d12014-06-30 21:05:18 +00001968 // See if we can find a thread for this signal.
1969 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1970 if (!thread_sp)
1971 {
1972 if (log)
1973 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1974 }
1975
1976 // Handle the signal.
1977 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1978 {
1979 if (log)
1980 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1981 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001982 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001983 signo,
1984 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1985 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001986 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001987 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001988 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001989
Todd Fiala58a2f662014-08-12 17:02:07 +00001990 // Check for new thread notification.
1991 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1992 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001993 // A new thread creation is being signaled. This is one of two parts that come in
1994 // a non-deterministic order. This code handles the case where the new thread event comes
1995 // before the event on the parent thread. For the opposite case see code in
1996 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00001997 if (log)
1998 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
1999 __FUNCTION__, GetID (), pid);
2000
Pavel Labath5fd24c62015-04-23 09:04:35 +00002001 thread_sp = AddThread(pid);
2002 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2003 // We can now resume the newly created thread.
2004 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2005 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002006 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002007 // Done handling.
2008 return;
2009 }
2010
2011 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002012 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002013 {
2014 // This is a tgkill()-based stop.
2015 if (thread_sp)
2016 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002017 if (log)
2018 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2019 __FUNCTION__,
2020 GetID (),
2021 pid);
2022
Chaoren Linaab58632015-02-03 01:50:57 +00002023 // Check that we're not already marked with a stop reason.
2024 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2025 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2026 // and that, without an intervening resume, we received another stop. It is more likely
2027 // that we are missing the marking of a run state somewhere if we find that the thread was
2028 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002029 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2030 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002031
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002032 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002033 if (!StateIsStoppedState (thread_state, false))
2034 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002035 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2036 // Generally, these are not important stops and we don't want to report them as
2037 // they are just used to stop other threads when one thread (the one with the
2038 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2039 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2040 // leave the signal intact if this is the thread that was chosen as the
2041 // triggering thread.
2042 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002043 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002044 else
2045 linux_thread_sp->SetStoppedBySignal(0);
2046
Chaoren Linaab58632015-02-03 01:50:57 +00002047 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002048 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002049 }
2050 else
2051 {
2052 if (log)
2053 {
2054 // Retrieve the signal name if the thread was stopped by a signal.
2055 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002056 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002057 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
Chaoren Linaab58632015-02-03 01:50:57 +00002058 if (!signal_name)
2059 signal_name = "<no-signal-name>";
2060
2061 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",
2062 __FUNCTION__,
2063 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002064 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002065 StateAsCString (thread_state),
2066 stop_signo,
2067 signal_name);
2068 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002069 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002070 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002071 }
2072
2073 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002074 return;
2075 }
2076
2077 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002078 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00002079
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002080 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002081 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002082
Pavel Labathc4e25c92015-05-29 10:13:03 +00002083 if (thread_sp)
2084 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002085
2086 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002087 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002088}
2089
Tamas Berghammere7708682015-04-22 10:00:23 +00002090namespace {
2091
2092struct EmulatorBaton
2093{
2094 NativeProcessLinux* m_process;
2095 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002096
Pavel Labath6648fcc2015-04-27 09:21:14 +00002097 // eRegisterKindDWARF -> RegsiterValue
2098 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2099
2100 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002101 m_process(process), m_reg_context(reg_context) {}
2102};
2103
2104} // anonymous namespace
2105
2106static size_t
2107ReadMemoryCallback (EmulateInstruction *instruction,
2108 void *baton,
2109 const EmulateInstruction::Context &context,
2110 lldb::addr_t addr,
2111 void *dst,
2112 size_t length)
2113{
2114 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2115
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002116 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002117 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2118 return bytes_read;
2119}
2120
2121static bool
2122ReadRegisterCallback (EmulateInstruction *instruction,
2123 void *baton,
2124 const RegisterInfo *reg_info,
2125 RegisterValue &reg_value)
2126{
2127 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2128
Pavel Labath6648fcc2015-04-27 09:21:14 +00002129 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2130 if (it != emulator_baton->m_register_values.end())
2131 {
2132 reg_value = it->second;
2133 return true;
2134 }
2135
Tamas Berghammere7708682015-04-22 10:00:23 +00002136 // The emulator only fill in the dwarf regsiter numbers (and in some case
2137 // the generic register numbers). Get the full register info from the
2138 // register context based on the dwarf register numbers.
2139 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2140 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2141
2142 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002143 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002144 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002145
Pavel Labath6648fcc2015-04-27 09:21:14 +00002146 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002147}
2148
2149static bool
2150WriteRegisterCallback (EmulateInstruction *instruction,
2151 void *baton,
2152 const EmulateInstruction::Context &context,
2153 const RegisterInfo *reg_info,
2154 const RegisterValue &reg_value)
2155{
2156 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002157 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002158 return true;
2159}
2160
2161static size_t
2162WriteMemoryCallback (EmulateInstruction *instruction,
2163 void *baton,
2164 const EmulateInstruction::Context &context,
2165 lldb::addr_t addr,
2166 const void *dst,
2167 size_t length)
2168{
2169 return length;
2170}
2171
2172static lldb::addr_t
2173ReadFlags (NativeRegisterContext* regsiter_context)
2174{
2175 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2176 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2177 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2178}
2179
2180Error
2181NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2182{
2183 Error error;
2184 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2185
2186 std::unique_ptr<EmulateInstruction> emulator_ap(
2187 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2188
2189 if (emulator_ap == nullptr)
2190 return Error("Instruction emulator not found!");
2191
2192 EmulatorBaton baton(this, register_context_sp.get());
2193 emulator_ap->SetBaton(&baton);
2194 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2195 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2196 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2197 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2198
2199 if (!emulator_ap->ReadInstruction())
2200 return Error("Read instruction failed!");
2201
Pavel Labath6648fcc2015-04-27 09:21:14 +00002202 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2203
2204 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2205 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2206
2207 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2208 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2209
Tamas Berghammere7708682015-04-22 10:00:23 +00002210 lldb::addr_t next_pc;
2211 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002212 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002213 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002214 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2215 next_pc = pc_it->second.GetAsUInt64();
2216
2217 if (flags_it != baton.m_register_values.end())
2218 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002219 else
2220 next_flags = ReadFlags (register_context_sp.get());
2221 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002222 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002223 {
2224 // Emulate instruction failed and it haven't changed PC. Advance PC
2225 // with the size of the current opcode because the emulation of all
2226 // PC modifying instruction should be successful. The failure most
2227 // likely caused by a not supported instruction which don't modify PC.
2228 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2229 next_flags = ReadFlags (register_context_sp.get());
2230 }
2231 else
2232 {
2233 // The instruction emulation failed after it modified the PC. It is an
2234 // unknown error where we can't continue because the next instruction is
2235 // modifying the PC but we don't know how.
2236 return Error ("Instruction emulation failed unexpectedly.");
2237 }
2238
2239 if (m_arch.GetMachine() == llvm::Triple::arm)
2240 {
2241 if (next_flags & 0x20)
2242 {
2243 // Thumb mode
2244 error = SetSoftwareBreakpoint(next_pc, 2);
2245 }
2246 else
2247 {
2248 // Arm mode
2249 error = SetSoftwareBreakpoint(next_pc, 4);
2250 }
2251 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002252 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002253 || m_arch.GetMachine() == llvm::Triple::mips64el
2254 || m_arch.GetMachine() == llvm::Triple::mips
2255 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002256 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002257 else
2258 {
2259 // No size hint is given for the next breakpoint
2260 error = SetSoftwareBreakpoint(next_pc, 0);
2261 }
2262
Tamas Berghammere7708682015-04-22 10:00:23 +00002263 if (error.Fail())
2264 return error;
2265
2266 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2267
2268 return Error();
2269}
2270
2271bool
2272NativeProcessLinux::SupportHardwareSingleStepping() const
2273{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002274 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002275 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
2276 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002277 return false;
2278 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002279}
2280
Todd Fialaaf245d12014-06-30 21:05:18 +00002281Error
2282NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2283{
Todd Fialaaf245d12014-06-30 21:05:18 +00002284 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2285 if (log)
2286 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2287
Tamas Berghammere7708682015-04-22 10:00:23 +00002288 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002289
Pavel Labath45f5cb32015-05-05 15:05:50 +00002290 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002291 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002292
Tamas Berghammere7708682015-04-22 10:00:23 +00002293 if (software_single_step)
2294 {
2295 for (auto thread_sp : m_threads)
2296 {
2297 assert (thread_sp && "thread list should not contain NULL threads");
2298
2299 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2300 if (action == nullptr)
2301 continue;
2302
2303 if (action->state == eStateStepping)
2304 {
2305 Error error = SetupSoftwareSingleStepping(thread_sp);
2306 if (error.Fail())
2307 return error;
2308 }
2309 }
2310 }
2311
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002312 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002313 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002314 assert (thread_sp && "thread list should not contain NULL threads");
2315
2316 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2317
2318 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002319 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002320 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002321 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2322 __FUNCTION__, GetID (), thread_sp->GetID ());
2323 continue;
2324 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002325
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002326 if (log)
2327 {
2328 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2329 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2330 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002331
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002332 switch (action->state)
2333 {
2334 case eStateRunning:
2335 {
2336 // Run the thread, possibly feeding it the signal.
2337 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002338 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002339 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2340 {
2341 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2342 // Pass this signal number on to the inferior to handle.
2343 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2344 if (resume_result.Success())
2345 SetState(eStateRunning, true);
2346 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002347 },
2348 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002349 break;
2350 }
2351
2352 case eStateStepping:
2353 {
2354 // Request the step.
2355 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002356 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002357 [=](lldb::tid_t tid_to_step, bool supress_signal)
2358 {
2359 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002360
Pavel Labathc0765592015-05-06 10:46:34 +00002361 Error step_result;
2362 if (software_single_step)
2363 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2364 else
2365 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002366
Pavel Labathc0765592015-05-06 10:46:34 +00002367 assert (step_result.Success() && "SingleStep() failed");
2368 if (step_result.Success())
2369 SetState(eStateStepping, true);
2370 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002371 },
2372 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002373 break;
2374 }
2375
2376 case eStateSuspended:
2377 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002378 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002379
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002380 default:
2381 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2382 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002383 }
2384 }
2385
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002386 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002387}
2388
2389Error
2390NativeProcessLinux::Halt ()
2391{
2392 Error error;
2393
Todd Fialaaf245d12014-06-30 21:05:18 +00002394 if (kill (GetID (), SIGSTOP) != 0)
2395 error.SetErrorToErrno ();
2396
2397 return error;
2398}
2399
2400Error
2401NativeProcessLinux::Detach ()
2402{
2403 Error error;
2404
2405 // Tell ptrace to detach from the process.
2406 if (GetID () != LLDB_INVALID_PROCESS_ID)
2407 error = Detach (GetID ());
2408
2409 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00002410 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002411
2412 // No error.
2413 return error;
2414}
2415
2416Error
2417NativeProcessLinux::Signal (int signo)
2418{
2419 Error error;
2420
2421 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2422 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002423 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2424 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00002425
2426 if (kill(GetID(), signo))
2427 error.SetErrorToErrno();
2428
2429 return error;
2430}
2431
2432Error
Chaoren Line9547b82015-02-03 01:51:00 +00002433NativeProcessLinux::Interrupt ()
2434{
2435 // Pick a running thread (or if none, a not-dead stopped thread) as
2436 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002437 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2438
2439 NativeThreadProtocolSP running_thread_sp;
2440 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002441
2442 if (log)
2443 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2444
Pavel Labath45f5cb32015-05-05 15:05:50 +00002445 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002446 Mutex::Locker locker (m_threads_mutex);
2447
2448 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002449 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002450 // The thread shouldn't be null but lets just cover that here.
2451 if (!thread_sp)
2452 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002453
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002454 // If we have a running or stepping thread, we'll call that the
2455 // target of the interrupt.
2456 const auto thread_state = thread_sp->GetState ();
2457 if (thread_state == eStateRunning ||
2458 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002459 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002460 running_thread_sp = thread_sp;
2461 break;
2462 }
2463 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2464 {
2465 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2466 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002467 }
2468 }
2469
2470 if (!running_thread_sp && !stopped_thread_sp)
2471 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002472 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002473 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002474 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002475
Chaoren Line9547b82015-02-03 01:51:00 +00002476 return error;
2477 }
2478
2479 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2480
2481 if (log)
2482 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2483 __FUNCTION__,
2484 GetID (),
2485 running_thread_sp ? "running" : "stopped",
2486 deferred_signal_thread_sp->GetID ());
2487
Pavel Labathed89c7f2015-05-06 12:22:37 +00002488 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002489
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002490 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002491}
2492
2493Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002494NativeProcessLinux::Kill ()
2495{
2496 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2497 if (log)
2498 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2499
2500 Error error;
2501
2502 switch (m_state)
2503 {
2504 case StateType::eStateInvalid:
2505 case StateType::eStateExited:
2506 case StateType::eStateCrashed:
2507 case StateType::eStateDetached:
2508 case StateType::eStateUnloaded:
2509 // Nothing to do - the process is already dead.
2510 if (log)
2511 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2512 return error;
2513
2514 case StateType::eStateConnected:
2515 case StateType::eStateAttaching:
2516 case StateType::eStateLaunching:
2517 case StateType::eStateStopped:
2518 case StateType::eStateRunning:
2519 case StateType::eStateStepping:
2520 case StateType::eStateSuspended:
2521 // We can try to kill a process in these states.
2522 break;
2523 }
2524
2525 if (kill (GetID (), SIGKILL) != 0)
2526 {
2527 error.SetErrorToErrno ();
2528 return error;
2529 }
2530
2531 return error;
2532}
2533
2534static Error
2535ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2536{
2537 memory_region_info.Clear();
2538
2539 StringExtractor line_extractor (maps_line.c_str ());
2540
2541 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2542 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2543
2544 // Parse out the starting address
2545 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2546
2547 // Parse out hyphen separating start and end address from range.
2548 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2549 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2550
2551 // Parse out the ending address
2552 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2553
2554 // Parse out the space after the address.
2555 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2556 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2557
2558 // Save the range.
2559 memory_region_info.GetRange ().SetRangeBase (start_address);
2560 memory_region_info.GetRange ().SetRangeEnd (end_address);
2561
2562 // Parse out each permission entry.
2563 if (line_extractor.GetBytesLeft () < 4)
2564 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2565
2566 // Handle read permission.
2567 const char read_perm_char = line_extractor.GetChar ();
2568 if (read_perm_char == 'r')
2569 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2570 else
2571 {
2572 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2573 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2574 }
2575
2576 // Handle write permission.
2577 const char write_perm_char = line_extractor.GetChar ();
2578 if (write_perm_char == 'w')
2579 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2580 else
2581 {
2582 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2583 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2584 }
2585
2586 // Handle execute permission.
2587 const char exec_perm_char = line_extractor.GetChar ();
2588 if (exec_perm_char == 'x')
2589 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2590 else
2591 {
2592 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2593 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2594 }
2595
2596 return Error ();
2597}
2598
2599Error
2600NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2601{
2602 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2603 // with no perms if it is not mapped.
2604
2605 // Use an approach that reads memory regions from /proc/{pid}/maps.
2606 // Assume proc maps entries are in ascending order.
2607 // FIXME assert if we find differently.
2608 Mutex::Locker locker (m_mem_region_cache_mutex);
2609
2610 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2611 Error error;
2612
2613 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2614 {
2615 // We're done.
2616 error.SetErrorString ("unsupported");
2617 return error;
2618 }
2619
2620 // If our cache is empty, pull the latest. There should always be at least one memory region
2621 // if memory region handling is supported.
2622 if (m_mem_region_cache.empty ())
2623 {
2624 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2625 [&] (const std::string &line) -> bool
2626 {
2627 MemoryRegionInfo info;
2628 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2629 if (parse_error.Success ())
2630 {
2631 m_mem_region_cache.push_back (info);
2632 return true;
2633 }
2634 else
2635 {
2636 if (log)
2637 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2638 return false;
2639 }
2640 });
2641
2642 // If we had an error, we'll mark unsupported.
2643 if (error.Fail ())
2644 {
2645 m_supports_mem_region = LazyBool::eLazyBoolNo;
2646 return error;
2647 }
2648 else if (m_mem_region_cache.empty ())
2649 {
2650 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2651 // is supported. Assume we don't support map entries via procfs.
2652 if (log)
2653 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2654 m_supports_mem_region = LazyBool::eLazyBoolNo;
2655 error.SetErrorString ("not supported");
2656 return error;
2657 }
2658
2659 if (log)
2660 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2661
2662 // We support memory retrieval, remember that.
2663 m_supports_mem_region = LazyBool::eLazyBoolYes;
2664 }
2665 else
2666 {
2667 if (log)
2668 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2669 }
2670
2671 lldb::addr_t prev_base_address = 0;
2672
2673 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2674 // There can be a ton of regions on pthreads apps with lots of threads.
2675 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2676 {
2677 MemoryRegionInfo &proc_entry_info = *it;
2678
2679 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2680 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2681 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2682
2683 // If the target address comes before this entry, indicate distance to next region.
2684 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2685 {
2686 range_info.GetRange ().SetRangeBase (load_addr);
2687 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2688 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2689 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2690 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2691
2692 return error;
2693 }
2694 else if (proc_entry_info.GetRange ().Contains (load_addr))
2695 {
2696 // The target address is within the memory region we're processing here.
2697 range_info = proc_entry_info;
2698 return error;
2699 }
2700
2701 // The target memory address comes somewhere after the region we just parsed.
2702 }
2703
Tamas Berghammer09839c32015-07-03 09:30:19 +00002704 // If we made it here, we didn't find an entry that contained the given address. Return the
2705 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2706 // size.
2707 range_info.GetRange ().SetRangeBase (load_addr);
2708 switch (m_arch.GetAddressByteSize())
2709 {
2710 case 4:
2711 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2712 break;
2713 case 8:
2714 range_info.GetRange ().SetByteSize (0ull - load_addr);
2715 break;
2716 default:
2717 assert(false && "Unrecognized data byte size");
2718 break;
2719 }
2720 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2721 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2722 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002723 return error;
2724}
2725
2726void
2727NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2728{
2729 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2730 if (log)
2731 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2732
2733 {
2734 Mutex::Locker locker (m_mem_region_cache_mutex);
2735 if (log)
2736 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2737 m_mem_region_cache.clear ();
2738 }
2739}
2740
2741Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002742NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002743{
2744 // FIXME implementing this requires the equivalent of
2745 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2746 // functional ThreadPlans working with Native*Protocol.
2747#if 1
2748 return Error ("not implemented yet");
2749#else
2750 addr = LLDB_INVALID_ADDRESS;
2751
2752 unsigned prot = 0;
2753 if (permissions & lldb::ePermissionsReadable)
2754 prot |= eMmapProtRead;
2755 if (permissions & lldb::ePermissionsWritable)
2756 prot |= eMmapProtWrite;
2757 if (permissions & lldb::ePermissionsExecutable)
2758 prot |= eMmapProtExec;
2759
2760 // TODO implement this directly in NativeProcessLinux
2761 // (and lift to NativeProcessPOSIX if/when that class is
2762 // refactored out).
2763 if (InferiorCallMmap(this, addr, 0, size, prot,
2764 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2765 m_addr_to_mmap_size[addr] = size;
2766 return Error ();
2767 } else {
2768 addr = LLDB_INVALID_ADDRESS;
2769 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2770 }
2771#endif
2772}
2773
2774Error
2775NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2776{
2777 // FIXME see comments in AllocateMemory - required lower-level
2778 // bits not in place yet (ThreadPlans)
2779 return Error ("not implemented");
2780}
2781
2782lldb::addr_t
2783NativeProcessLinux::GetSharedLibraryInfoAddress ()
2784{
2785#if 1
2786 // punt on this for now
2787 return LLDB_INVALID_ADDRESS;
2788#else
2789 // Return the image info address for the exe module
2790#if 1
2791 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2792
2793 ModuleSP module_sp;
2794 Error error = GetExeModuleSP (module_sp);
2795 if (error.Fail ())
2796 {
2797 if (log)
2798 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2799 return LLDB_INVALID_ADDRESS;
2800 }
2801
2802 if (module_sp == nullptr)
2803 {
2804 if (log)
2805 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2806 return LLDB_INVALID_ADDRESS;
2807 }
2808
2809 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2810 if (object_file_sp == nullptr)
2811 {
2812 if (log)
2813 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2814 return LLDB_INVALID_ADDRESS;
2815 }
2816
2817 return obj_file_sp->GetImageInfoAddress();
2818#else
2819 Target *target = &GetTarget();
2820 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2821 Address addr = obj_file->GetImageInfoAddress(target);
2822
2823 if (addr.IsValid())
2824 return addr.GetLoadAddress(target);
2825 return LLDB_INVALID_ADDRESS;
2826#endif
2827#endif // punt on this for now
2828}
2829
2830size_t
2831NativeProcessLinux::UpdateThreads ()
2832{
2833 // The NativeProcessLinux monitoring threads are always up to date
2834 // with respect to thread state and they keep the thread list
2835 // populated properly. All this method needs to do is return the
2836 // thread count.
2837 Mutex::Locker locker (m_threads_mutex);
2838 return m_threads.size ();
2839}
2840
2841bool
2842NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2843{
2844 arch = m_arch;
2845 return true;
2846}
2847
2848Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002849NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002850{
2851 // FIXME put this behind a breakpoint protocol class that can be
2852 // set per architecture. Need ARM, MIPS support here.
2853 static const uint8_t g_i386_opcode [] = { 0xCC };
2854
2855 switch (m_arch.GetMachine ())
2856 {
2857 case llvm::Triple::x86:
2858 case llvm::Triple::x86_64:
2859 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2860 return Error ();
2861
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002862 case llvm::Triple::arm:
2863 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002864 case llvm::Triple::mips64:
2865 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002866 case llvm::Triple::mips:
2867 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002868 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002869 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002870 return Error ();
2871
Todd Fialaaf245d12014-06-30 21:05:18 +00002872 default:
2873 assert(false && "CPU type not supported!");
2874 return Error ("CPU type not supported");
2875 }
2876}
2877
2878Error
2879NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2880{
2881 if (hardware)
2882 return Error ("NativeProcessLinux does not support hardware breakpoints");
2883 else
2884 return SetSoftwareBreakpoint (addr, size);
2885}
2886
2887Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002888NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2889 size_t &actual_opcode_size,
2890 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002891{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002892 // FIXME put this behind a breakpoint protocol class that can be set per
2893 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002894 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002895 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2896 // linux kernel does otherwise.
2897 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002898 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002899 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002900 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002901 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002902
2903 switch (m_arch.GetMachine ())
2904 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002905 case llvm::Triple::aarch64:
2906 trap_opcode_bytes = g_aarch64_opcode;
2907 actual_opcode_size = sizeof(g_aarch64_opcode);
2908 return Error ();
2909
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002910 case llvm::Triple::arm:
2911 switch (trap_opcode_size_hint)
2912 {
2913 case 2:
2914 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2915 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2916 return Error ();
2917 case 4:
2918 trap_opcode_bytes = g_arm_breakpoint_opcode;
2919 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2920 return Error ();
2921 default:
2922 assert(false && "Unrecognised trap opcode size hint!");
2923 return Error ("Unrecognised trap opcode size hint!");
2924 }
2925
Todd Fialaaf245d12014-06-30 21:05:18 +00002926 case llvm::Triple::x86:
2927 case llvm::Triple::x86_64:
2928 trap_opcode_bytes = g_i386_opcode;
2929 actual_opcode_size = sizeof(g_i386_opcode);
2930 return Error ();
2931
Sagar Thakurce815e42015-06-03 10:14:24 +00002932 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002933 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002934 trap_opcode_bytes = g_mips64_opcode;
2935 actual_opcode_size = sizeof(g_mips64_opcode);
2936 return Error ();
2937
Sagar Thakurce815e42015-06-03 10:14:24 +00002938 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002939 case llvm::Triple::mips64el:
2940 trap_opcode_bytes = g_mips64el_opcode;
2941 actual_opcode_size = sizeof(g_mips64el_opcode);
2942 return Error ();
2943
Todd Fialaaf245d12014-06-30 21:05:18 +00002944 default:
2945 assert(false && "CPU type not supported!");
2946 return Error ("CPU type not supported");
2947 }
2948}
2949
2950#if 0
2951ProcessMessage::CrashReason
2952NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2953{
2954 ProcessMessage::CrashReason reason;
2955 assert(info->si_signo == SIGSEGV);
2956
2957 reason = ProcessMessage::eInvalidCrashReason;
2958
2959 switch (info->si_code)
2960 {
2961 default:
2962 assert(false && "unexpected si_code for SIGSEGV");
2963 break;
2964 case SI_KERNEL:
2965 // Linux will occasionally send spurious SI_KERNEL codes.
2966 // (this is poorly documented in sigaction)
2967 // One way to get this is via unaligned SIMD loads.
2968 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2969 break;
2970 case SEGV_MAPERR:
2971 reason = ProcessMessage::eInvalidAddress;
2972 break;
2973 case SEGV_ACCERR:
2974 reason = ProcessMessage::ePrivilegedAddress;
2975 break;
2976 }
2977
2978 return reason;
2979}
2980#endif
2981
2982
2983#if 0
2984ProcessMessage::CrashReason
2985NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2986{
2987 ProcessMessage::CrashReason reason;
2988 assert(info->si_signo == SIGILL);
2989
2990 reason = ProcessMessage::eInvalidCrashReason;
2991
2992 switch (info->si_code)
2993 {
2994 default:
2995 assert(false && "unexpected si_code for SIGILL");
2996 break;
2997 case ILL_ILLOPC:
2998 reason = ProcessMessage::eIllegalOpcode;
2999 break;
3000 case ILL_ILLOPN:
3001 reason = ProcessMessage::eIllegalOperand;
3002 break;
3003 case ILL_ILLADR:
3004 reason = ProcessMessage::eIllegalAddressingMode;
3005 break;
3006 case ILL_ILLTRP:
3007 reason = ProcessMessage::eIllegalTrap;
3008 break;
3009 case ILL_PRVOPC:
3010 reason = ProcessMessage::ePrivilegedOpcode;
3011 break;
3012 case ILL_PRVREG:
3013 reason = ProcessMessage::ePrivilegedRegister;
3014 break;
3015 case ILL_COPROC:
3016 reason = ProcessMessage::eCoprocessorError;
3017 break;
3018 case ILL_BADSTK:
3019 reason = ProcessMessage::eInternalStackError;
3020 break;
3021 }
3022
3023 return reason;
3024}
3025#endif
3026
3027#if 0
3028ProcessMessage::CrashReason
3029NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3030{
3031 ProcessMessage::CrashReason reason;
3032 assert(info->si_signo == SIGFPE);
3033
3034 reason = ProcessMessage::eInvalidCrashReason;
3035
3036 switch (info->si_code)
3037 {
3038 default:
3039 assert(false && "unexpected si_code for SIGFPE");
3040 break;
3041 case FPE_INTDIV:
3042 reason = ProcessMessage::eIntegerDivideByZero;
3043 break;
3044 case FPE_INTOVF:
3045 reason = ProcessMessage::eIntegerOverflow;
3046 break;
3047 case FPE_FLTDIV:
3048 reason = ProcessMessage::eFloatDivideByZero;
3049 break;
3050 case FPE_FLTOVF:
3051 reason = ProcessMessage::eFloatOverflow;
3052 break;
3053 case FPE_FLTUND:
3054 reason = ProcessMessage::eFloatUnderflow;
3055 break;
3056 case FPE_FLTRES:
3057 reason = ProcessMessage::eFloatInexactResult;
3058 break;
3059 case FPE_FLTINV:
3060 reason = ProcessMessage::eFloatInvalidOperation;
3061 break;
3062 case FPE_FLTSUB:
3063 reason = ProcessMessage::eFloatSubscriptRange;
3064 break;
3065 }
3066
3067 return reason;
3068}
3069#endif
3070
3071#if 0
3072ProcessMessage::CrashReason
3073NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3074{
3075 ProcessMessage::CrashReason reason;
3076 assert(info->si_signo == SIGBUS);
3077
3078 reason = ProcessMessage::eInvalidCrashReason;
3079
3080 switch (info->si_code)
3081 {
3082 default:
3083 assert(false && "unexpected si_code for SIGBUS");
3084 break;
3085 case BUS_ADRALN:
3086 reason = ProcessMessage::eIllegalAlignment;
3087 break;
3088 case BUS_ADRERR:
3089 reason = ProcessMessage::eIllegalAddress;
3090 break;
3091 case BUS_OBJERR:
3092 reason = ProcessMessage::eHardwareError;
3093 break;
3094 }
3095
3096 return reason;
3097}
3098#endif
3099
Todd Fialaaf245d12014-06-30 21:05:18 +00003100Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003101NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3102{
3103 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3104 // for it.
3105 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3106 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3107}
3108
3109Error
3110NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3111{
3112 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3113 // for it.
3114 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3115 return NativeProcessProtocol::RemoveWatchpoint(addr);
3116}
3117
3118Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003119NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003120{
Pavel Labathdf7c6992015-06-17 18:38:49 +00003121 if (ProcessVmReadvSupported()) {
3122 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3123 // this syscall if it is supported.
3124
3125 const ::pid_t pid = GetID();
3126
3127 struct iovec local_iov, remote_iov;
3128 local_iov.iov_base = buf;
3129 local_iov.iov_len = size;
3130 remote_iov.iov_base = reinterpret_cast<void *>(addr);
3131 remote_iov.iov_len = size;
3132
3133 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3134 const bool success = bytes_read == size;
3135
3136 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3137 if (log)
3138 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3139 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3140
3141 if (success)
3142 return Error();
3143 // else
3144 // the call failed for some reason, let's retry the read using ptrace api.
3145 }
3146
Pavel Labathc7512fd2015-06-26 10:14:12 +00003147 return DoOperation([&] { return DoReadMemory(GetID(), addr, buf, size, bytes_read); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003148}
3149
3150Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003151NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3152{
3153 Error error = ReadMemory(addr, buf, size, bytes_read);
3154 if (error.Fail()) return error;
3155 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3156}
3157
3158Error
3159NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003160{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003161 return DoOperation([&] { return DoWriteMemory(GetID(), addr, buf, size, bytes_written); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003162}
3163
Chaoren Lin97ccc292015-02-03 01:51:12 +00003164Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003165NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3166{
Todd Fialaaf245d12014-06-30 21:05:18 +00003167 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3168
3169 if (log)
3170 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003171 Host::GetSignalAsCString(signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00003172
3173
3174
3175 intptr_t data = 0;
3176
3177 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3178 data = signo;
3179
Pavel Labath4a9babb2015-06-30 17:04:49 +00003180 Error error = DoOperation([&] { return PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data); });
Pavel Labathc7512fd2015-06-26 10:14:12 +00003181
Todd Fialaaf245d12014-06-30 21:05:18 +00003182 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00003183 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
3184 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00003185}
3186
Chaoren Lin97ccc292015-02-03 01:51:12 +00003187Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003188NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3189{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003190 intptr_t data = 0;
3191
3192 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3193 data = signo;
3194
Pavel Labath4a9babb2015-06-30 17:04:49 +00003195 return DoOperation([&] { return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003196}
3197
Chaoren Lin97ccc292015-02-03 01:51:12 +00003198Error
3199NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003200{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003201 return DoOperation([&] { return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003202}
3203
Chaoren Lin97ccc292015-02-03 01:51:12 +00003204Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003205NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3206{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003207 return DoOperation([&] { return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003208}
3209
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003210Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003211NativeProcessLinux::Detach(lldb::tid_t tid)
3212{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003213 if (tid == LLDB_INVALID_THREAD_ID)
3214 return Error();
3215
Pavel Labath4a9babb2015-06-30 17:04:49 +00003216 return DoOperation([&] { return PtraceWrapper(PTRACE_DETACH, tid); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003217}
3218
3219bool
Chaoren Lind3173f32015-05-29 19:52:29 +00003220NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00003221{
Chaoren Lind3173f32015-05-29 19:52:29 +00003222 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00003223
3224 if (target_fd == -1)
3225 return false;
3226
Pavel Labath493c3a12015-02-04 10:36:57 +00003227 if (dup2(target_fd, fd) == -1)
3228 return false;
3229
3230 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003231}
3232
3233void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003234NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003235{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003236 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003237 error = m_monitor_up->Initialize();
3238 if (error.Fail()) {
3239 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003240 }
3241}
3242
Todd Fialaaf245d12014-06-30 21:05:18 +00003243bool
3244NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3245{
3246 for (auto thread_sp : m_threads)
3247 {
3248 assert (thread_sp && "thread list should not contain NULL threads");
3249 if (thread_sp->GetID () == thread_id)
3250 {
3251 // We have this thread.
3252 return true;
3253 }
3254 }
3255
3256 // We don't have this thread.
3257 return false;
3258}
3259
3260NativeThreadProtocolSP
3261NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3262{
3263 // CONSIDER organize threads by map - we can do better than linear.
3264 for (auto thread_sp : m_threads)
3265 {
3266 if (thread_sp->GetID () == thread_id)
3267 return thread_sp;
3268 }
3269
3270 // We don't have this thread.
3271 return NativeThreadProtocolSP ();
3272}
3273
3274bool
3275NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3276{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003277 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3278
3279 if (log)
3280 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3281
3282 bool found = false;
3283
Todd Fialaaf245d12014-06-30 21:05:18 +00003284 Mutex::Locker locker (m_threads_mutex);
3285 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3286 {
3287 if (*it && ((*it)->GetID () == thread_id))
3288 {
3289 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003290 found = true;
3291 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003292 }
3293 }
3294
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003295 // If we have a pending notification, remove this from the set.
3296 if (m_pending_notification_up)
3297 {
3298 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003299 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003300 }
3301
3302 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003303}
3304
3305NativeThreadProtocolSP
3306NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3307{
3308 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3309
3310 Mutex::Locker locker (m_threads_mutex);
3311
3312 if (log)
3313 {
3314 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3315 __FUNCTION__,
3316 GetID (),
3317 thread_id);
3318 }
3319
3320 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3321
3322 // If this is the first thread, save it as the current thread
3323 if (m_threads.empty ())
3324 SetCurrentThreadID (thread_id);
3325
3326 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3327 m_threads.push_back (thread_sp);
3328
3329 return thread_sp;
3330}
3331
Todd Fialaaf245d12014-06-30 21:05:18 +00003332Error
3333NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3334{
Todd Fiala75f47c32014-10-11 21:42:09 +00003335 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003336
3337 Error error;
3338
3339 // Get a linux thread pointer.
3340 if (!thread_sp)
3341 {
3342 error.SetErrorString ("null thread_sp");
3343 if (log)
3344 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3345 return error;
3346 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003347 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003348
3349 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003350 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003351 if (!context_sp)
3352 {
3353 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3354 if (log)
3355 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3356 return error;
3357 }
3358
3359 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003360 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003361 if (error.Fail ())
3362 {
3363 if (log)
3364 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3365 return error;
3366 }
3367 else
3368 {
3369 if (log)
3370 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3371 }
3372
3373 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00003374 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003375 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003376 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003377 {
3378 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003379 if (breakpoint_addr >= breakpoint_size)
3380 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003381 }
3382
3383 // Check if we stopped because of a breakpoint.
3384 NativeBreakpointSP breakpoint_sp;
3385 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3386 if (!error.Success () || !breakpoint_sp)
3387 {
3388 // We didn't find one at a software probe location. Nothing to do.
3389 if (log)
3390 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3391 return Error ();
3392 }
3393
3394 // If the breakpoint is not a software breakpoint, nothing to do.
3395 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3396 {
3397 if (log)
3398 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3399 return Error ();
3400 }
3401
3402 //
3403 // We have a software breakpoint and need to adjust the PC.
3404 //
3405
3406 // Sanity check.
3407 if (breakpoint_size == 0)
3408 {
3409 // Nothing to do! How did we get here?
3410 if (log)
3411 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);
3412 return Error ();
3413 }
3414
3415 // Change the program counter.
3416 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003417 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 +00003418
3419 error = context_sp->SetPC (breakpoint_addr);
3420 if (error.Fail ())
3421 {
3422 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003423 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 +00003424 return error;
3425 }
3426
3427 return error;
3428}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003429
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003430Error
3431NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3432{
3433 char maps_file_name[32];
3434 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3435
3436 FileSpec maps_file_spec(maps_file_name, false);
3437 if (!maps_file_spec.Exists()) {
3438 file_spec.Clear();
3439 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3440 }
3441
3442 FileSpec module_file_spec(module_path, true);
3443
3444 std::ifstream maps_file(maps_file_name);
3445 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3446 StringRef maps_data(maps_data_str.c_str());
3447
3448 while (!maps_data.empty())
3449 {
3450 StringRef maps_row;
3451 std::tie(maps_row, maps_data) = maps_data.split('\n');
3452
3453 SmallVector<StringRef, 16> maps_columns;
3454 maps_row.split(maps_columns, StringRef(" "), -1, false);
3455
3456 if (maps_columns.size() >= 6)
3457 {
3458 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3459 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3460 return Error();
3461 }
3462 }
3463
3464 file_spec.Clear();
3465 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3466 module_file_spec.GetFilename().AsCString(), GetID());
3467}
Pavel Labathc0765592015-05-06 10:46:34 +00003468
Pavel Labath5eb721e2015-05-07 08:30:31 +00003469Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003470NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3471{
3472 load_addr = LLDB_INVALID_ADDRESS;
3473 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3474 [&] (const std::string &line) -> bool
3475 {
3476 StringRef maps_row(line);
3477
3478 SmallVector<StringRef, 16> maps_columns;
3479 maps_row.split(maps_columns, StringRef(" "), -1, false);
3480
3481 if (maps_columns.size() < 6)
3482 {
3483 // Return true to continue reading the proc file
3484 return true;
3485 }
3486
3487 if (maps_columns[5] == file_name)
3488 {
3489 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3490 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3491
3492 // Return false to stop reading the proc file further
3493 return false;
3494 }
3495
3496 // Return true to continue reading the proc file
3497 return true;
3498 });
3499 return error;
3500}
3501
3502Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003503NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003504 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003505 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003506 bool error_when_already_running)
3507{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003508 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003509
3510 if (log)
3511 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3512 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003513
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003514 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3515 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003516
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003517 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003518 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003519 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003520
3521 lldbassert(!(error_when_already_running && !is_stopped));
3522
Pavel Labathc0765592015-05-06 10:46:34 +00003523 if (!is_stopped)
3524 {
3525 // It's not an error, just a log, if the error_when_already_running flag is not set.
3526 // This covers cases where, for instance, we're just trying to resume all threads
3527 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003528 if (log)
3529 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3530 __FUNCTION__,
3531 tid);
3532 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003533 }
3534
3535 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003536 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003537 // this thread to stop. This is potentially a buggy situation since
3538 // we're ostensibly waiting for threads to stop before we send out the
3539 // pending notification, and here we are resuming one before we send
3540 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003541 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003542 {
Pavel Labath108c3252015-05-12 09:03:18 +00003543 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 +00003544 }
3545
3546 // Request a resume. We expect this to be synchronous and the system
3547 // to reflect it is running after this completes.
3548 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003549 if (error.Success())
3550 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003551 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003552 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003553 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003554 __FUNCTION__, tid, error.AsCString ());
3555 }
3556
Pavel Labath5eb721e2015-05-07 08:30:31 +00003557 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003558}
3559
3560//===----------------------------------------------------------------------===//
3561
3562void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003563NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003564{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003565 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003566
Pavel Labath5eb721e2015-05-07 08:30:31 +00003567 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003568 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003569 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003570 __FUNCTION__, triggering_tid);
3571 }
3572
Pavel Labath337f3eb2015-05-08 08:57:45 +00003573 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
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 event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003578 }
3579}
3580
3581void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003582NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003583{
3584 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3585 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003586 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3587
3588 // Clear any temporary breakpoints we used to implement software single stepping.
3589 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3590 {
3591 Error error = RemoveBreakpoint (thread_info.second);
3592 if (error.Fail())
3593 if (log)
3594 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3595 __FUNCTION__, thread_info.first, error.AsCString());
3596 }
3597 m_threads_stepping_with_breakpoint.clear();
3598
3599 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003600 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3601 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003602 m_pending_notification_up.reset();
3603 }
3604}
3605
Pavel Labathc0765592015-05-06 10:46:34 +00003606void
3607NativeProcessLinux::RequestStopOnAllRunningThreads()
3608{
3609 // Request a stop for all the thread stops that need to be stopped
3610 // and are not already known to be stopped. Keep a list of all the
3611 // threads from which we still need to hear a stop reply.
3612
3613 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003614 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003615 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003616 // We only care about running threads
3617 if (StateIsStoppedState(thread_sp->GetState(), true))
3618 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003619
Pavel Labath108c3252015-05-12 09:03:18 +00003620 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3621 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003622 }
3623
3624 // Set the wait list to the set of tids for which we requested stops.
3625 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3626}
3627
Pavel Labathc0765592015-05-06 10:46:34 +00003628
Pavel Labath5eb721e2015-05-07 08:30:31 +00003629Error
3630NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003631{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003632 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3633
3634 if (log)
3635 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3636 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3637
Pavel Labathc0765592015-05-06 10:46:34 +00003638 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003639 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3640 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003641
3642 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003643 auto& context = thread_sp->GetThreadContext();
3644 const auto stop_was_requested = context.stop_requested;
3645 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003646
3647 // If we have a pending notification, remove this from the set.
3648 if (m_pending_notification_up)
3649 {
3650 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003651 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003652 }
3653
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003654 Error error;
3655 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003656 {
3657 // We can end up here if stop was initiated by LLGS but by this time a
3658 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003659 if (log)
3660 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003661 error = context.request_resume_function (tid, true);
3662 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003663 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003664 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3665 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003666 }
3667 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003668 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003669}
3670
3671void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003672NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003673{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003674 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3675 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003676 {
3677 // Yikes - we've already got a pending signal notification in progress.
3678 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003679 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 +00003680 __FUNCTION__,
3681 m_pending_notification_up->triggering_tid,
3682 notification_up->triggering_tid);
3683 }
3684 m_pending_notification_up = std::move(notification_up);
3685
Pavel Labath108c3252015-05-12 09:03:18 +00003686 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003687
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003688 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003689}
3690
3691void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003692NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003693{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003694 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3695
3696 if (log)
3697 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3698
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003699 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3700 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003701
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003702 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003703 {
3704 // We will need to wait for this new thread to stop as well before firing the
3705 // notification.
3706 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003707 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003708 }
3709}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003710
3711Error
Pavel Labathc7512fd2015-06-26 10:14:12 +00003712NativeProcessLinux::DoOperation(const Operation &op)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003713{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003714 return m_monitor_up->DoOperation(op);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003715}
3716
3717// Wrapper for ptrace to catch errors and log calls.
3718// 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 +00003719Error
3720NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003721{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003722 Error error;
3723 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003724
3725 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3726
3727 PtraceDisplayBytes(req, data, data_size);
3728
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003729 errno = 0;
3730 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003731 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003732 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003733 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003734
Pavel Labath4a9babb2015-06-30 17:04:49 +00003735 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003736 error.SetErrorToErrno();
3737
Pavel Labath4a9babb2015-06-30 17:04:49 +00003738 if (result)
3739 *result = ret;
3740
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003741 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003742 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003743
3744 PtraceDisplayBytes(req, data, data_size);
3745
3746 if (log && error.GetError() != 0)
3747 {
3748 const char* str;
3749 switch (error.GetError())
3750 {
3751 case ESRCH: str = "ESRCH"; break;
3752 case EINVAL: str = "EINVAL"; break;
3753 case EBUSY: str = "EBUSY"; break;
3754 case EPERM: str = "EPERM"; break;
3755 default: str = error.AsCString();
3756 }
3757 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3758 }
3759
Pavel Labath4a9babb2015-06-30 17:04:49 +00003760 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003761}