blob: 85638720b9ab1788f1e55d293476efdfb5cb2636 [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 Labath5abe7262015-07-16 08:45:03 +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
Pavel Labath5abe7262015-07-16 08:45:03 +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
221 Error
222 DoReadMemory(
223 lldb::pid_t pid,
224 lldb::addr_t vm_addr,
225 void *buf,
226 size_t size,
227 size_t &bytes_read)
228 {
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);
232 size_t remainder;
233 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 {
245 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, &data);
246 if (error.Fail())
247 {
248 if (log)
249 ProcessPOSIXLog::DecNestLevel();
250 return error;
251 }
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 }
272 vm_addr += word_size;
273 dst += word_size;
274 }
275
276 if (log)
277 ProcessPOSIXLog::DecNestLevel();
278 return Error();
279 }
280
281 Error
282 DoWriteMemory(
283 lldb::pid_t pid,
284 lldb::addr_t vm_addr,
285 const void *buf,
286 size_t size,
287 size_t &bytes_written)
288 {
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);
292 size_t remainder;
293 Error error;
294
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__,
319 (void*)vm_addr, *(const unsigned long*)src, data);
320
321 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data);
322 if (error.Fail())
323 {
324 if (log)
325 ProcessPOSIXLog::DecNestLevel();
326 return error;
327 }
328 }
329 else
330 {
331 unsigned char buff[8];
332 size_t bytes_read;
333 error = DoReadMemory(pid, vm_addr, buff, word_size, bytes_read);
334 if (error.Fail())
335 {
336 if (log)
337 ProcessPOSIXLog::DecNestLevel();
338 return error;
339 }
340
341 memcpy(buff, src, remainder);
342
343 size_t bytes_written_rec;
344 error = DoWriteMemory(pid, vm_addr, buff, word_size, bytes_written_rec);
345 if (error.Fail())
346 {
347 if (log)
348 ProcessPOSIXLog::DecNestLevel();
349 return error;
350 }
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__,
357 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
358 }
359
360 vm_addr += word_size;
361 src += word_size;
362 }
363 if (log)
364 ProcessPOSIXLog::DecNestLevel();
365 return error;
366 }
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
Pavel Labath5abe7262015-07-16 08:45:03 +0000392// 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.
402class NativeProcessLinux::Monitor
403{
404private:
405 // 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;
410
411 enum { READ, WRITE };
412 int m_pipefd[2] = {-1, -1};
413 int m_signal_fd = -1;
414 HostThread m_thread;
415
416 // current operation which must be executed on the priviliged thread
417 Mutex m_operation_mutex;
418 const Operation *m_operation = nullptr;
419 sem_t m_operation_sem;
420 Error m_operation_error;
421
422 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 = '}';
427
428 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
444 Error
445 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
461public:
462 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 }
469
470 ~Monitor();
471
472 Error
473 Initialize();
474
475 void
476 Terminate();
477
478 Error
479 DoOperation(const Operation &op);
480
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 };
492};
493constexpr char NativeProcessLinux::Monitor::operation_command;
494constexpr char NativeProcessLinux::Monitor::begin_block_command;
495constexpr char NativeProcessLinux::Monitor::end_block_command;
496
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
522 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);
528 if (!m_thread.IsJoinable())
529 return Error("Failed to create monitor thread for NativeProcessLinux.");
530
531 // Wait for initial operation to complete.
532 return WaitForAck();
533}
534
535Error
536NativeProcessLinux::Monitor::DoOperation(const Operation &op)
537{
538 if (m_thread.EqualsThread(pthread_self())) {
539 // If we're on the Monitor thread, we can simply execute the operation.
540 return op();
541 }
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
546 m_operation = &op;
547
548 // notify the thread that an operation is ready to be processed
549 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
550
551 return WaitForAck();
552}
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);
564}
565
566NativeProcessLinux::Monitor::~Monitor()
567{
568 Terminate();
569 if (m_pipefd[READ] >= 0)
570 close(m_pipefd[READ]);
571 if (m_signal_fd >= 0)
572 close(m_signal_fd);
573 sem_destroy(&m_operation_sem);
574}
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;
623 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
624
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)
634 log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
635 __FUNCTION__, strerror(errno));
636 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";
658 if (wait_pid == m_child_pid) {
659 exited = true;
660 exit_status = -1;
661 }
662 }
663 else
664 status_cstr = "(\?\?\?)";
665
666 if (log)
667 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
668 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
669 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
670
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__);
698 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
699 return true; // We are done.
700 }
701
702 switch (command)
703 {
704 case operation_command:
705 m_operation_error = (*m_operation)();
706 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;
713 break;
714 default:
715 if (log)
716 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
717 __FUNCTION__, command);
718 }
719
720 // notify calling thread that the command has been processed
721 sem_post(&m_operation_sem);
722 }
723}
724
725void
726NativeProcessLinux::Monitor::MainLoop()
727{
728 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
729 m_initial_operation_up.reset();
730 m_child_pid = child_pid;
731 sem_post(&m_operation_sem);
732
733 while (true)
734 {
735 fd_set fds;
736 FD_ZERO(&fds);
737 // 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);
741 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 {
Pavel Labath44e82db2015-07-20 16:14:46 +0000747 if (errno == EINTR)
748 continue;
749
Pavel Labath5abe7262015-07-16 08:45:03 +0000750 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
751 if (log)
752 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
753 __FUNCTION__, strerror(errno));
754 return;
755 }
756
757 if (FD_ISSET(m_pipefd[READ], &fds))
758 {
759 if (HandleCommands())
760 return;
761 }
762
763 if (FD_ISSET(m_signal_fd, &fds))
764 {
765 HandleSignals();
766 HandleWait();
767 }
768 }
769}
770
771Error
772NativeProcessLinux::Monitor::WaitForAck()
773{
774 Error error;
775 while (sem_wait(&m_operation_sem) != 0)
776 {
777 if (errno == EINTR)
778 continue;
779
780 error.SetErrorToErrno();
781 return error;
782 }
783
784 return m_operation_error;
785}
786
787void *
788NativeProcessLinux::Monitor::RunMonitor(void *arg)
789{
790 static_cast<Monitor *>(arg)->MainLoop();
791 return nullptr;
792}
793
794
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000795NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000796 char const **argv,
797 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000798 const FileSpec &stdin_file_spec,
799 const FileSpec &stdout_file_spec,
800 const FileSpec &stderr_file_spec,
801 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000802 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000803 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000804 m_argv(argv),
805 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000806 m_stdin_file_spec(stdin_file_spec),
807 m_stdout_file_spec(stdout_file_spec),
808 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000809 m_working_dir(working_dir),
810 m_launch_info(launch_info)
811{
812}
Todd Fialaaf245d12014-06-30 21:05:18 +0000813
814NativeProcessLinux::LaunchArgs::~LaunchArgs()
815{ }
816
Todd Fialaaf245d12014-06-30 21:05:18 +0000817// -----------------------------------------------------------------------------
818// Public Static Methods
819// -----------------------------------------------------------------------------
820
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000821Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000822NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000823 ProcessLaunchInfo &launch_info,
824 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000825 NativeProcessProtocolSP &native_process_sp)
826{
827 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
828
Pavel Labathd5b310f2015-07-09 11:51:11 +0000829 lldb::ModuleSP exe_module_sp;
830 PlatformSP platform_sp (Platform::GetHostPlatform ());
831 Error error = platform_sp->ResolveExecutable(
832 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
833 exe_module_sp,
834 nullptr);
835
836 if (! error.Success())
837 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000838
839 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000840 FileSpec working_dir{launch_info.GetWorkingDirectory()};
841 if (working_dir &&
842 (!working_dir.ResolvePath() ||
843 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000844 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000845 error.SetErrorStringWithFormat ("No such file or directory: %s",
846 working_dir.GetCString());
847 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000848 }
849
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000850 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000851
Chaoren Lind3173f32015-05-29 19:52:29 +0000852 // Default of empty will mean to use existing open file descriptors.
853 FileSpec stdin_file_spec{};
854 FileSpec stdout_file_spec{};
855 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000856
857 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000858 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000859 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000860
861 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000862 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000863 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000864
865 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000866 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000867 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000868
869 if (log)
870 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000871 if (stdin_file_spec)
872 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
873 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000874 else
875 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
876
Chaoren Lind3173f32015-05-29 19:52:29 +0000877 if (stdout_file_spec)
878 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
879 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000880 else
881 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
882
Chaoren Lind3173f32015-05-29 19:52:29 +0000883 if (stderr_file_spec)
884 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
885 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000886 else
887 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
888 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000889
890 // Create the NativeProcessLinux in launch mode.
891 native_process_sp.reset (new NativeProcessLinux ());
892
893 if (log)
894 {
895 int i = 0;
896 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
897 {
898 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
899 ++i;
900 }
901 }
902
903 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
904 {
905 native_process_sp.reset ();
906 error.SetErrorStringWithFormat ("failed to register the native delegate");
907 return error;
908 }
909
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000910 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labathd5b310f2015-07-09 11:51:11 +0000911 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000912 launch_info.GetArguments ().GetConstArgumentVector (),
913 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000914 stdin_file_spec,
915 stdout_file_spec,
916 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000917 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000918 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000919 error);
920
921 if (error.Fail ())
922 {
923 native_process_sp.reset ();
924 if (log)
925 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
926 return error;
927 }
928
929 launch_info.SetProcessID (native_process_sp->GetID ());
930
931 return error;
932}
933
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000934Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000935NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000936 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000937 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000938 NativeProcessProtocolSP &native_process_sp)
939{
940 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
941 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
942 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
943
944 // Grab the current platform architecture. This should be Linux,
945 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000946 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000947 if (!platform_sp)
948 return Error("failed to get a valid default platform");
949
950 // Retrieve the architecture for the running process.
951 ArchSpec process_arch;
952 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
953 if (!error.Success ())
954 return error;
955
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000956 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000957
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000958 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000959 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000960 error.SetErrorStringWithFormat ("failed to register the native delegate");
961 return error;
962 }
963
Pavel Labath5abe7262015-07-16 08:45:03 +0000964 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000965 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000966 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000967
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000968 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000969 return error;
970}
971
972// -----------------------------------------------------------------------------
973// Public Instance Methods
974// -----------------------------------------------------------------------------
975
976NativeProcessLinux::NativeProcessLinux () :
977 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
978 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000979 m_supports_mem_region (eLazyBoolCalculate),
980 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +0000981 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000982{
983}
984
Pavel Labath5abe7262015-07-16 08:45:03 +0000985//------------------------------------------------------------------------------
986// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
987// Refer to Monitor and Operation classes to see why this is necessary.
988//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000989void
990NativeProcessLinux::LaunchInferior (
991 Module *module,
992 const char *argv[],
993 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000994 const FileSpec &stdin_file_spec,
995 const FileSpec &stdout_file_spec,
996 const FileSpec &stderr_file_spec,
997 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000998 const ProcessLaunchInfo &launch_info,
999 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001000{
1001 if (module)
1002 m_arch = module->GetArchitecture ();
1003
Chaoren Linfa03ad22015-02-03 01:50:42 +00001004 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001005
1006 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +00001007 new LaunchArgs(module, argv, envp,
1008 stdin_file_spec,
1009 stdout_file_spec,
1010 stderr_file_spec,
1011 working_dir,
1012 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001013
Pavel Labath5abe7262015-07-16 08:45:03 +00001014 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
1015 if (!error.Success ())
1016 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001017}
1018
1019void
Pavel Labath5abe7262015-07-16 08:45:03 +00001020NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001021{
1022 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1023 if (log)
1024 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1025
1026 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001027 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001028 if (!platform_sp)
1029 {
1030 if (log)
1031 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1032 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001033 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001034 }
1035
1036 // Gather info about the process.
1037 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001038 if (!platform_sp->GetProcessInfo (pid, process_info))
1039 {
1040 if (log)
1041 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1042 error.SetErrorString ("failed to get process info");
1043 return;
1044 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001045
1046 // Resolve the executable module
1047 ModuleSP exe_module_sp;
1048 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001049 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001050 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001051 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001052 if (!error.Success())
1053 return;
1054
1055 // Set the architecture to the exe architecture.
1056 m_arch = exe_module_sp->GetArchitecture();
1057 if (log)
1058 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1059
1060 m_pid = pid;
1061 SetState(eStateAttaching);
1062
Pavel Labath5abe7262015-07-16 08:45:03 +00001063 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
1064 if (!error.Success ())
1065 return;
1066}
1067
1068void
1069NativeProcessLinux::Terminate ()
1070{
1071 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001072}
1073
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001074::pid_t
1075NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001076{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001077 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001078
1079 const char **argv = args->m_argv;
1080 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +00001081 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +00001082
1083 lldb_utility::PseudoTerminal terminal;
1084 const size_t err_len = 1024;
1085 char err_str[err_len];
1086 lldb::pid_t pid;
1087 NativeThreadProtocolSP thread_sp;
1088
1089 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001090
1091 // Propagate the environment if one is not supplied.
1092 if (envp == NULL || envp[0] == NULL)
1093 envp = const_cast<const char **>(environ);
1094
1095 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1096 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001097 error.SetErrorToGenericError();
1098 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1099 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001100 }
1101
1102 // Recognized child exit status codes.
1103 enum {
1104 ePtraceFailed = 1,
1105 eDupStdinFailed,
1106 eDupStdoutFailed,
1107 eDupStderrFailed,
1108 eChdirFailed,
1109 eExecFailed,
1110 eSetGidFailed
1111 };
1112
1113 // Child process.
1114 if (pid == 0)
1115 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001116 // FIXME consider opening a pipe between parent/child and have this forked child
1117 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001118
Todd Fiala75f47c32014-10-11 21:42:09 +00001119 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001120 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001121 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001122 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001123
Pavel Labath493c3a12015-02-04 10:36:57 +00001124 // terminal has already dupped the tty descriptors to stdin/out/err.
1125 // This closes original fd from which they were copied (and avoids
1126 // leaking descriptors to the debugged process.
1127 terminal.CloseSlaveFileDescriptor();
1128
Todd Fialaaf245d12014-06-30 21:05:18 +00001129 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001130 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001131 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001132
1133 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001134 if (setpgid(0, 0) != 0)
1135 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001136 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001137 // Don't allow this to prevent an inferior exec.
1138 }
1139
1140 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +00001141 if (args->m_stdin_file_spec)
1142 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001143 exit(eDupStdinFailed);
1144
Chaoren Lind3173f32015-05-29 19:52:29 +00001145 if (args->m_stdout_file_spec)
1146 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001147 exit(eDupStdoutFailed);
1148
Chaoren Lind3173f32015-05-29 19:52:29 +00001149 if (args->m_stderr_file_spec)
1150 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001151 exit(eDupStderrFailed);
1152
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001153 // Close everything besides stdin, stdout, and stderr that has no file
1154 // action to avoid leaking
1155 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1156 if (!args->m_launch_info.GetFileActionForFD(fd))
1157 close(fd);
1158
Todd Fialaaf245d12014-06-30 21:05:18 +00001159 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +00001160 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +00001161 exit(eChdirFailed);
1162
Todd Fiala0bce1b62014-08-17 00:10:50 +00001163 // Disable ASLR if requested.
1164 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1165 {
1166 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1167 if (old_personality == -1)
1168 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001169 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001170 }
1171 else
1172 {
1173 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1174 if (new_personality == -1)
1175 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001176 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001177 }
1178 else
1179 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001180 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001181 }
1182 }
1183 }
1184
Todd Fiala75f47c32014-10-11 21:42:09 +00001185 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001186 execve(argv[0],
1187 const_cast<char *const *>(argv),
1188 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001189
1190 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001191 exit(eExecFailed);
1192 }
1193
Todd Fiala75f47c32014-10-11 21:42:09 +00001194 //
1195 // This is the parent code here.
1196 //
1197 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1198
Todd Fialaaf245d12014-06-30 21:05:18 +00001199 // Wait for the child process to trap on its call to execve.
1200 ::pid_t wpid;
1201 int status;
1202 if ((wpid = waitpid(pid, &status, 0)) < 0)
1203 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001204 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001205 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001206 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1207 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001208
1209 // Mark the inferior as invalid.
1210 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001211 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001212
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001213 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001214 }
1215 else if (WIFEXITED(status))
1216 {
1217 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001218 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001219 switch (WEXITSTATUS(status))
1220 {
1221 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001222 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001223 break;
1224 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001225 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001226 break;
1227 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001228 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001229 break;
1230 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001231 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 break;
1233 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001234 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001235 break;
1236 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001237 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001238 break;
1239 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001240 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 break;
1242 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001243 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001244 break;
1245 }
1246
1247 if (log)
1248 {
1249 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1250 __FUNCTION__,
1251 WEXITSTATUS(status));
1252 }
1253
1254 // Mark the inferior as invalid.
1255 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001256 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001257
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001258 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001260 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001261 "Could not sync with inferior process.");
1262
1263 if (log)
1264 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1265
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001266 error = SetDefaultPtraceOpts(pid);
1267 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001268 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001269 if (log)
1270 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001271 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001272
1273 // Mark the inferior as invalid.
1274 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001275 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001276
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001277 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001278 }
1279
1280 // Release the master terminal descriptor and pass it off to the
1281 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001282 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1283 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001284
1285 // Set the terminal fd to be in non blocking mode (it simplifies the
1286 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1287 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001288 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1289 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001290 {
1291 if (log)
1292 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001293 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001294
1295 // Mark the inferior as invalid.
1296 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001297 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001298
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001299 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001300 }
1301
1302 if (log)
1303 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1304
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001305 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001306 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001307 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001308 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001309
1310 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001311 SetCurrentThreadID (thread_sp->GetID ());
1312 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001313
Todd Fialaaf245d12014-06-30 21:05:18 +00001314 if (log)
1315 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001316 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001317 {
1318 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1319 }
1320 else
1321 {
1322 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001323 __FUNCTION__, error.AsCString ());
1324 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001325 }
1326 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001327 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001328}
1329
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001330::pid_t
1331NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001332{
Todd Fialaaf245d12014-06-30 21:05:18 +00001333 lldb::ThreadSP inferior;
1334 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1335
1336 // Use a map to keep track of the threads which we have attached/need to attach.
1337 Host::TidMap tids_to_attach;
1338 if (pid <= 1)
1339 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001340 error.SetErrorToGenericError();
1341 error.SetErrorString("Attaching to process 1 is not allowed.");
1342 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001343 }
1344
1345 while (Host::FindProcessThreads(pid, tids_to_attach))
1346 {
1347 for (Host::TidMap::iterator it = tids_to_attach.begin();
1348 it != tids_to_attach.end();)
1349 {
1350 if (it->second == false)
1351 {
1352 lldb::tid_t tid = it->first;
1353
1354 // Attach to the requested process.
1355 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +00001356 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001357 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001358 {
1359 // No such thread. The thread may have exited.
1360 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001361 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001362 {
1363 it = tids_to_attach.erase(it);
1364 continue;
1365 }
1366 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001367 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001368 }
1369
1370 int status;
1371 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1372 // At this point we should have a thread stopped if waitpid succeeds.
1373 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1374 {
1375 // No such thread. The thread may have exited.
1376 // More error handling may be needed.
1377 if (errno == ESRCH)
1378 {
1379 it = tids_to_attach.erase(it);
1380 continue;
1381 }
1382 else
1383 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001384 error.SetErrorToErrno();
1385 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001386 }
1387 }
1388
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001389 error = SetDefaultPtraceOpts(tid);
1390 if (error.Fail())
1391 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001392
1393 if (log)
1394 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1395
1396 it->second = true;
1397
1398 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001399 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001400 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001401
1402 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001403 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001404 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001405 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001406 }
1407
1408 // move the loop forward
1409 ++it;
1410 }
1411 }
1412
1413 if (tids_to_attach.size() > 0)
1414 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001415 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001416 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001417 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001418 }
1419 else
1420 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001421 error.SetErrorToGenericError();
1422 error.SetErrorString("No such process.");
1423 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001424 }
1425
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001426 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001427}
1428
Chaoren Lin97ccc292015-02-03 01:51:12 +00001429Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001430NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1431{
1432 long ptrace_opts = 0;
1433
1434 // Have the child raise an event on exit. This is used to keep the child in
1435 // limbo until it is destroyed.
1436 ptrace_opts |= PTRACE_O_TRACEEXIT;
1437
1438 // Have the tracer trace threads which spawn in the inferior process.
1439 // TODO: if we want to support tracing the inferiors' child, add the
1440 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1441 ptrace_opts |= PTRACE_O_TRACECLONE;
1442
1443 // Have the tracer notify us before execve returns
1444 // (needed to disable legacy SIGTRAP generation)
1445 ptrace_opts |= PTRACE_O_TRACEEXEC;
1446
Pavel Labath4a9babb2015-06-30 17:04:49 +00001447 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +00001448}
1449
1450static ExitType convert_pid_status_to_exit_type (int status)
1451{
1452 if (WIFEXITED (status))
1453 return ExitType::eExitTypeExit;
1454 else if (WIFSIGNALED (status))
1455 return ExitType::eExitTypeSignal;
1456 else if (WIFSTOPPED (status))
1457 return ExitType::eExitTypeStop;
1458 else
1459 {
1460 // We don't know what this is.
1461 return ExitType::eExitTypeInvalid;
1462 }
1463}
1464
1465static int convert_pid_status_to_return_code (int status)
1466{
1467 if (WIFEXITED (status))
1468 return WEXITSTATUS (status);
1469 else if (WIFSIGNALED (status))
1470 return WTERMSIG (status);
1471 else if (WIFSTOPPED (status))
1472 return WSTOPSIG (status);
1473 else
1474 {
1475 // We don't know what this is.
1476 return ExitType::eExitTypeInvalid;
1477 }
1478}
1479
Pavel Labath1107b5a2015-04-17 14:07:49 +00001480// Handles all waitpid events from the inferior process.
1481void
1482NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001483 bool exited,
1484 int signal,
1485 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001486{
1487 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1488
Todd Fialaaf245d12014-06-30 21:05:18 +00001489 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001490 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001491
1492 // Handle when the thread exits.
1493 if (exited)
1494 {
1495 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001496 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 +00001497
1498 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001499 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001500
1501 if (is_main_thread)
1502 {
1503 // We only set the exit status and notify the delegate if we haven't already set the process
1504 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1505 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001506 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001507 if (!already_notified)
1508 {
1509 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001510 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 +00001511 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001512 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001513
1514 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001515 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001516 }
1517 else
1518 {
1519 if (log)
1520 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1521 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001522 }
1523 else
1524 {
1525 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1526 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1527 // and we would have done an all-stop then.
1528 if (log)
1529 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 +00001530 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001531 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001532 }
1533
1534 // Get details on the signal raised.
1535 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001536 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001537 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001538 {
1539 // We have retrieved the signal info. Dispatch appropriately.
1540 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001541 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001542 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001543 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001544 }
1545 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001546 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001547 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001548 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001549 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001550 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1551 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1552 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1553 // generally not needed (one use case is debugging background task being managed by a
1554 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1555 // stop which happens before the group stop. This done by MonitorSignal and works
1556 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001557 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001558 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);
1559 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001560 }
1561 else
1562 {
1563 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1564
1565 // A return value of ESRCH means the thread/process is no longer on the system,
1566 // so it was killed somehow outside of our control. Either way, we can't do anything
1567 // with it anymore.
1568
Todd Fialaaf245d12014-06-30 21:05:18 +00001569 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001570 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001571
1572 if (log)
1573 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001574 __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 +00001575
1576 if (is_main_thread)
1577 {
1578 // Notify the delegate - our process is not available but appears to have been killed outside
1579 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001580 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1581 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001582 }
1583 else
1584 {
1585 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1586 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001587 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 +00001588 }
1589 }
1590 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001591}
1592
1593void
Pavel Labath426bdf82015-04-28 07:51:52 +00001594NativeProcessLinux::WaitForNewThread(::pid_t tid)
1595{
1596 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1597
1598 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1599
1600 if (new_thread_sp)
1601 {
1602 // We are already tracking the thread - we got the event on the new thread (see
1603 // MonitorSignal) before this one. We are done.
1604 return;
1605 }
1606
1607 // The thread is not tracked yet, let's wait for it to appear.
1608 int status = -1;
1609 ::pid_t wait_pid;
1610 do
1611 {
1612 if (log)
1613 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1614 wait_pid = waitpid(tid, &status, __WALL);
1615 }
1616 while (wait_pid == -1 && errno == EINTR);
1617 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1618 // some checks just in case.
1619 if (wait_pid != tid) {
1620 if (log)
1621 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1622 // The only way I know of this could happen is if the whole process was
1623 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1624 return;
1625 }
1626 if (WIFEXITED(status))
1627 {
1628 if (log)
1629 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1630 // Also a very improbable event.
1631 return;
1632 }
1633
1634 siginfo_t info;
1635 Error error = GetSignalInfo(tid, &info);
1636 if (error.Fail())
1637 {
1638 if (log)
1639 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1640 return;
1641 }
1642
1643 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1644 {
1645 // We should be getting a thread creation signal here, but we received something
1646 // else. There isn't much we can do about it now, so we will just log that. Since the
1647 // thread is alive and we are receiving events from it, we shall pretend that it was
1648 // created properly.
1649 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);
1650 }
1651
1652 if (log)
1653 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1654 __FUNCTION__, GetID (), tid);
1655
1656 new_thread_sp = AddThread(tid);
1657 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1658 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001659 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001660}
1661
1662void
Todd Fialaaf245d12014-06-30 21:05:18 +00001663NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1664{
1665 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1666 const bool is_main_thread = (pid == GetID ());
1667
1668 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1669 if (!info)
1670 return;
1671
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001672 Mutex::Locker locker (m_threads_mutex);
1673
Todd Fialaaf245d12014-06-30 21:05:18 +00001674 // See if we can find a thread for this signal.
1675 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1676 if (!thread_sp)
1677 {
1678 if (log)
1679 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1680 }
1681
1682 switch (info->si_code)
1683 {
1684 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1685 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1686 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1687
1688 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1689 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001690 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001691 // creation.
1692 // We don't want to do anything with the parent thread so we just resume it. In case we
1693 // want to implement "break on thread creation" functionality, we would need to stop
1694 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001695
Pavel Labath426bdf82015-04-28 07:51:52 +00001696 unsigned long event_message = 0;
1697 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001698 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001699 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001700 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 +00001701 } else
1702 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001703
Pavel Labath5fd24c62015-04-23 09:04:35 +00001704 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001705 break;
1706 }
1707
1708 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001709 {
1710 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001711 if (log)
1712 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001713
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001714 // Exec clears any pending notifications.
1715 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001716
1717 // 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 +00001718 if (log)
1719 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1720
1721 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001722 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001723 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1724 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001725 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001726 main_thread_sp = thread_sp;
1727 if (log)
1728 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001729 }
1730 else
1731 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001732 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001733 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001734 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001735 }
1736 }
1737
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001738 m_threads.clear ();
1739
1740 if (main_thread_sp)
1741 {
1742 m_threads.push_back (main_thread_sp);
1743 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001744 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001745 }
1746 else
1747 {
1748 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1749 if (log)
1750 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1751 }
1752
Chaoren Linfa03ad22015-02-03 01:50:42 +00001753 // Tell coordinator about about the "new" (since exec) stopped main thread.
1754 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001755 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001756
1757 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1758 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001759 // Let our delegate know we have just exec'd.
1760 NotifyDidExec ();
1761
1762 // If we have a main thread, indicate we are stopped.
1763 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001764
1765 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001766 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001767
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001769 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001770
1771 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1772 {
1773 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001774 // We don't want to do anything with the thread so we just resume it. In case we
1775 // want to implement "break on thread exit" functionality, we would need to stop
1776 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001777
Todd Fialaaf245d12014-06-30 21:05:18 +00001778 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001779 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001780 data = -1;
1781
1782 if (log)
1783 {
1784 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1785 __FUNCTION__,
1786 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1787 pid,
1788 is_main_thread ? "is main thread" : "not main thread");
1789 }
1790
Todd Fialaaf245d12014-06-30 21:05:18 +00001791 if (is_main_thread)
1792 {
1793 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001794 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001795
Pavel Labath6e351632015-05-15 13:30:59 +00001796 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001797
1798 break;
1799 }
1800
1801 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001802 case TRAP_TRACE: // We receive this on single stepping.
1803 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001804 if (thread_sp)
1805 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001806 // If a watchpoint was hit, report it
1807 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001808 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001809 if (error.Fail() && log)
1810 log->Printf("NativeProcessLinux::%s() "
1811 "received error while checking for watchpoint hits, "
1812 "pid = %" PRIu64 " error = %s",
1813 __FUNCTION__, pid, error.AsCString());
1814 if (wp_index != LLDB_INVALID_INDEX32)
1815 {
1816 MonitorWatchpoint(pid, thread_sp, wp_index);
1817 break;
1818 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001819 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001820 // Otherwise, report step over
1821 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001822 break;
1823
1824 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001825#if defined __mips__
1826 // For mips there is no special signal for watchpoint
1827 // So we check for watchpoint in kernel trap
1828 if (thread_sp)
1829 {
1830 // If a watchpoint was hit, report it
1831 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001832 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001833 if (error.Fail() && log)
1834 log->Printf("NativeProcessLinux::%s() "
1835 "received error while checking for watchpoint hits, "
1836 "pid = %" PRIu64 " error = %s",
1837 __FUNCTION__, pid, error.AsCString());
1838 if (wp_index != LLDB_INVALID_INDEX32)
1839 {
1840 MonitorWatchpoint(pid, thread_sp, wp_index);
1841 break;
1842 }
1843 }
1844 // NO BREAK
1845#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001847 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001848 break;
1849
1850 case SIGTRAP:
1851 case (SIGTRAP | 0x80):
1852 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001853 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1854
Todd Fialaaf245d12014-06-30 21:05:18 +00001855 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001856 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001857 break;
1858
1859 default:
1860 assert(false && "Unexpected SIGTRAP code!");
1861 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001862 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1863 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001864 break;
1865
1866 }
1867}
1868
1869void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001870NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1871{
1872 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1873 if (log)
1874 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1875 __FUNCTION__, pid);
1876
1877 if (thread_sp)
1878 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1879
1880 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001881 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001882
1883 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1884 // This would have already happened at the time the Resume() with step operation was signaled.
1885 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1886 // once all running threads have checked in as stopped.
1887 SetCurrentThreadID(pid);
1888 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001889 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001890}
1891
1892void
1893NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1894{
1895 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1896 if (log)
1897 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1898 __FUNCTION__, pid);
1899
1900 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001901 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001902
1903 // Mark the thread as stopped at breakpoint.
1904 if (thread_sp)
1905 {
1906 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1907 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1908 if (error.Fail())
1909 if (log)
1910 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1911 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001912
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001913 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001914 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001915 }
1916 else
1917 if (log)
1918 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1919 "warning, cannot process software breakpoint since no thread metadata",
1920 __FUNCTION__, pid);
1921
1922
1923 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001924 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001925}
1926
1927void
1928NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1929{
1930 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1931 if (log)
1932 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1933 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1934 __FUNCTION__, pid, wp_index);
1935
1936 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001937 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001938
1939 // Mark the thread as stopped at watchpoint.
1940 // The address is at (lldb::addr_t)info->si_addr if we need it.
1941 lldbassert(thread_sp && "thread_sp cannot be NULL");
1942 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1943
1944 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001945 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001946}
1947
1948void
Todd Fialaaf245d12014-06-30 21:05:18 +00001949NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1950{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001951 assert (info && "null info");
1952 if (!info)
1953 return;
1954
1955 const int signo = info->si_signo;
1956 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001957
1958 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1959
1960 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1961 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1962 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1963 //
1964 // IOW, user generated signals never generate what we consider to be a
1965 // "crash".
1966 //
1967 // Similarly, ACK signals generated by this monitor.
1968
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001969 Mutex::Locker locker (m_threads_mutex);
1970
Todd Fialaaf245d12014-06-30 21:05:18 +00001971 // See if we can find a thread for this signal.
1972 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1973 if (!thread_sp)
1974 {
1975 if (log)
1976 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1977 }
1978
1979 // Handle the signal.
1980 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1981 {
1982 if (log)
1983 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1984 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001985 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001986 signo,
1987 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1988 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001989 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001990 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001991 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001992
Todd Fiala58a2f662014-08-12 17:02:07 +00001993 // Check for new thread notification.
1994 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1995 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001996 // A new thread creation is being signaled. This is one of two parts that come in
1997 // a non-deterministic order. This code handles the case where the new thread event comes
1998 // before the event on the parent thread. For the opposite case see code in
1999 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002000 if (log)
2001 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2002 __FUNCTION__, GetID (), pid);
2003
Pavel Labath5fd24c62015-04-23 09:04:35 +00002004 thread_sp = AddThread(pid);
2005 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2006 // We can now resume the newly created thread.
2007 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2008 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002009 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002010 // Done handling.
2011 return;
2012 }
2013
2014 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002015 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002016 {
2017 // This is a tgkill()-based stop.
2018 if (thread_sp)
2019 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002020 if (log)
2021 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2022 __FUNCTION__,
2023 GetID (),
2024 pid);
2025
Chaoren Linaab58632015-02-03 01:50:57 +00002026 // Check that we're not already marked with a stop reason.
2027 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2028 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2029 // and that, without an intervening resume, we received another stop. It is more likely
2030 // that we are missing the marking of a run state somewhere if we find that the thread was
2031 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002032 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2033 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002034
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002035 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002036 if (!StateIsStoppedState (thread_state, false))
2037 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002038 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2039 // Generally, these are not important stops and we don't want to report them as
2040 // they are just used to stop other threads when one thread (the one with the
2041 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2042 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2043 // leave the signal intact if this is the thread that was chosen as the
2044 // triggering thread.
2045 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002046 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002047 else
2048 linux_thread_sp->SetStoppedBySignal(0);
2049
Chaoren Linaab58632015-02-03 01:50:57 +00002050 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002051 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002052 }
2053 else
2054 {
2055 if (log)
2056 {
2057 // Retrieve the signal name if the thread was stopped by a signal.
2058 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002059 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002060 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
Chaoren Linaab58632015-02-03 01:50:57 +00002061 if (!signal_name)
2062 signal_name = "<no-signal-name>";
2063
2064 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",
2065 __FUNCTION__,
2066 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002067 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002068 StateAsCString (thread_state),
2069 stop_signo,
2070 signal_name);
2071 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002072 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002073 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002074 }
2075
2076 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002077 return;
2078 }
2079
2080 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002081 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00002082
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002083 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002084 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002085
Pavel Labathc4e25c92015-05-29 10:13:03 +00002086 if (thread_sp)
2087 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002088
2089 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002090 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002091}
2092
Tamas Berghammere7708682015-04-22 10:00:23 +00002093namespace {
2094
2095struct EmulatorBaton
2096{
2097 NativeProcessLinux* m_process;
2098 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002099
Pavel Labath6648fcc2015-04-27 09:21:14 +00002100 // eRegisterKindDWARF -> RegsiterValue
2101 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2102
2103 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002104 m_process(process), m_reg_context(reg_context) {}
2105};
2106
2107} // anonymous namespace
2108
2109static size_t
2110ReadMemoryCallback (EmulateInstruction *instruction,
2111 void *baton,
2112 const EmulateInstruction::Context &context,
2113 lldb::addr_t addr,
2114 void *dst,
2115 size_t length)
2116{
2117 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2118
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002119 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002120 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2121 return bytes_read;
2122}
2123
2124static bool
2125ReadRegisterCallback (EmulateInstruction *instruction,
2126 void *baton,
2127 const RegisterInfo *reg_info,
2128 RegisterValue &reg_value)
2129{
2130 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2131
Pavel Labath6648fcc2015-04-27 09:21:14 +00002132 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2133 if (it != emulator_baton->m_register_values.end())
2134 {
2135 reg_value = it->second;
2136 return true;
2137 }
2138
Tamas Berghammere7708682015-04-22 10:00:23 +00002139 // The emulator only fill in the dwarf regsiter numbers (and in some case
2140 // the generic register numbers). Get the full register info from the
2141 // register context based on the dwarf register numbers.
2142 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2143 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2144
2145 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002146 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002147 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002148
Pavel Labath6648fcc2015-04-27 09:21:14 +00002149 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002150}
2151
2152static bool
2153WriteRegisterCallback (EmulateInstruction *instruction,
2154 void *baton,
2155 const EmulateInstruction::Context &context,
2156 const RegisterInfo *reg_info,
2157 const RegisterValue &reg_value)
2158{
2159 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002160 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002161 return true;
2162}
2163
2164static size_t
2165WriteMemoryCallback (EmulateInstruction *instruction,
2166 void *baton,
2167 const EmulateInstruction::Context &context,
2168 lldb::addr_t addr,
2169 const void *dst,
2170 size_t length)
2171{
2172 return length;
2173}
2174
2175static lldb::addr_t
2176ReadFlags (NativeRegisterContext* regsiter_context)
2177{
2178 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2179 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2180 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2181}
2182
2183Error
2184NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2185{
2186 Error error;
2187 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2188
2189 std::unique_ptr<EmulateInstruction> emulator_ap(
2190 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2191
2192 if (emulator_ap == nullptr)
2193 return Error("Instruction emulator not found!");
2194
2195 EmulatorBaton baton(this, register_context_sp.get());
2196 emulator_ap->SetBaton(&baton);
2197 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2198 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2199 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2200 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2201
2202 if (!emulator_ap->ReadInstruction())
2203 return Error("Read instruction failed!");
2204
Pavel Labath6648fcc2015-04-27 09:21:14 +00002205 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2206
2207 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2208 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2209
2210 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2211 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2212
Tamas Berghammere7708682015-04-22 10:00:23 +00002213 lldb::addr_t next_pc;
2214 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002215 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002216 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002217 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2218 next_pc = pc_it->second.GetAsUInt64();
2219
2220 if (flags_it != baton.m_register_values.end())
2221 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002222 else
2223 next_flags = ReadFlags (register_context_sp.get());
2224 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002225 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002226 {
2227 // Emulate instruction failed and it haven't changed PC. Advance PC
2228 // with the size of the current opcode because the emulation of all
2229 // PC modifying instruction should be successful. The failure most
2230 // likely caused by a not supported instruction which don't modify PC.
2231 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2232 next_flags = ReadFlags (register_context_sp.get());
2233 }
2234 else
2235 {
2236 // The instruction emulation failed after it modified the PC. It is an
2237 // unknown error where we can't continue because the next instruction is
2238 // modifying the PC but we don't know how.
2239 return Error ("Instruction emulation failed unexpectedly.");
2240 }
2241
2242 if (m_arch.GetMachine() == llvm::Triple::arm)
2243 {
2244 if (next_flags & 0x20)
2245 {
2246 // Thumb mode
2247 error = SetSoftwareBreakpoint(next_pc, 2);
2248 }
2249 else
2250 {
2251 // Arm mode
2252 error = SetSoftwareBreakpoint(next_pc, 4);
2253 }
2254 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002255 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002256 || m_arch.GetMachine() == llvm::Triple::mips64el
2257 || m_arch.GetMachine() == llvm::Triple::mips
2258 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002259 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002260 else
2261 {
2262 // No size hint is given for the next breakpoint
2263 error = SetSoftwareBreakpoint(next_pc, 0);
2264 }
2265
Tamas Berghammere7708682015-04-22 10:00:23 +00002266 if (error.Fail())
2267 return error;
2268
2269 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2270
2271 return Error();
2272}
2273
2274bool
2275NativeProcessLinux::SupportHardwareSingleStepping() const
2276{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002277 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002278 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
2279 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002280 return false;
2281 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002282}
2283
Todd Fialaaf245d12014-06-30 21:05:18 +00002284Error
2285NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2286{
Todd Fialaaf245d12014-06-30 21:05:18 +00002287 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2288 if (log)
2289 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2290
Tamas Berghammere7708682015-04-22 10:00:23 +00002291 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002292
Pavel Labath5abe7262015-07-16 08:45:03 +00002293 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002294 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002295
Tamas Berghammere7708682015-04-22 10:00:23 +00002296 if (software_single_step)
2297 {
2298 for (auto thread_sp : m_threads)
2299 {
2300 assert (thread_sp && "thread list should not contain NULL threads");
2301
2302 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2303 if (action == nullptr)
2304 continue;
2305
2306 if (action->state == eStateStepping)
2307 {
2308 Error error = SetupSoftwareSingleStepping(thread_sp);
2309 if (error.Fail())
2310 return error;
2311 }
2312 }
2313 }
2314
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002315 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002316 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002317 assert (thread_sp && "thread list should not contain NULL threads");
2318
2319 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2320
2321 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002322 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002323 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002324 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2325 __FUNCTION__, GetID (), thread_sp->GetID ());
2326 continue;
2327 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002328
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002329 if (log)
2330 {
2331 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2332 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2333 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002334
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002335 switch (action->state)
2336 {
2337 case eStateRunning:
2338 {
2339 // Run the thread, possibly feeding it the signal.
2340 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002341 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002342 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2343 {
2344 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2345 // Pass this signal number on to the inferior to handle.
2346 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2347 if (resume_result.Success())
2348 SetState(eStateRunning, true);
2349 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002350 },
2351 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002352 break;
2353 }
2354
2355 case eStateStepping:
2356 {
2357 // Request the step.
2358 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002359 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002360 [=](lldb::tid_t tid_to_step, bool supress_signal)
2361 {
2362 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002363
Pavel Labathc0765592015-05-06 10:46:34 +00002364 Error step_result;
2365 if (software_single_step)
2366 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2367 else
2368 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002369
Pavel Labathc0765592015-05-06 10:46:34 +00002370 assert (step_result.Success() && "SingleStep() failed");
2371 if (step_result.Success())
2372 SetState(eStateStepping, true);
2373 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002374 },
2375 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002376 break;
2377 }
2378
2379 case eStateSuspended:
2380 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002381 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002382
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002383 default:
2384 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2385 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002386 }
2387 }
2388
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002389 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002390}
2391
2392Error
2393NativeProcessLinux::Halt ()
2394{
2395 Error error;
2396
Todd Fialaaf245d12014-06-30 21:05:18 +00002397 if (kill (GetID (), SIGSTOP) != 0)
2398 error.SetErrorToErrno ();
2399
2400 return error;
2401}
2402
2403Error
2404NativeProcessLinux::Detach ()
2405{
2406 Error error;
2407
2408 // Tell ptrace to detach from the process.
2409 if (GetID () != LLDB_INVALID_PROCESS_ID)
2410 error = Detach (GetID ());
2411
2412 // Stop monitoring the inferior.
Pavel Labath5abe7262015-07-16 08:45:03 +00002413 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002414
2415 // No error.
2416 return error;
2417}
2418
2419Error
2420NativeProcessLinux::Signal (int signo)
2421{
2422 Error error;
2423
2424 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2425 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002426 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2427 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00002428
2429 if (kill(GetID(), signo))
2430 error.SetErrorToErrno();
2431
2432 return error;
2433}
2434
2435Error
Chaoren Line9547b82015-02-03 01:51:00 +00002436NativeProcessLinux::Interrupt ()
2437{
2438 // Pick a running thread (or if none, a not-dead stopped thread) as
2439 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002440 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2441
2442 NativeThreadProtocolSP running_thread_sp;
2443 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002444
2445 if (log)
2446 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2447
Pavel Labath5abe7262015-07-16 08:45:03 +00002448 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002449 Mutex::Locker locker (m_threads_mutex);
2450
2451 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002452 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002453 // The thread shouldn't be null but lets just cover that here.
2454 if (!thread_sp)
2455 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002456
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002457 // If we have a running or stepping thread, we'll call that the
2458 // target of the interrupt.
2459 const auto thread_state = thread_sp->GetState ();
2460 if (thread_state == eStateRunning ||
2461 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002462 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002463 running_thread_sp = thread_sp;
2464 break;
2465 }
2466 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2467 {
2468 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2469 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002470 }
2471 }
2472
2473 if (!running_thread_sp && !stopped_thread_sp)
2474 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002475 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002476 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002477 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002478
Chaoren Line9547b82015-02-03 01:51:00 +00002479 return error;
2480 }
2481
2482 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2483
2484 if (log)
2485 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2486 __FUNCTION__,
2487 GetID (),
2488 running_thread_sp ? "running" : "stopped",
2489 deferred_signal_thread_sp->GetID ());
2490
Pavel Labathed89c7f2015-05-06 12:22:37 +00002491 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002492
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002493 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002494}
2495
2496Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002497NativeProcessLinux::Kill ()
2498{
2499 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2500 if (log)
2501 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2502
2503 Error error;
2504
2505 switch (m_state)
2506 {
2507 case StateType::eStateInvalid:
2508 case StateType::eStateExited:
2509 case StateType::eStateCrashed:
2510 case StateType::eStateDetached:
2511 case StateType::eStateUnloaded:
2512 // Nothing to do - the process is already dead.
2513 if (log)
2514 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2515 return error;
2516
2517 case StateType::eStateConnected:
2518 case StateType::eStateAttaching:
2519 case StateType::eStateLaunching:
2520 case StateType::eStateStopped:
2521 case StateType::eStateRunning:
2522 case StateType::eStateStepping:
2523 case StateType::eStateSuspended:
2524 // We can try to kill a process in these states.
2525 break;
2526 }
2527
2528 if (kill (GetID (), SIGKILL) != 0)
2529 {
2530 error.SetErrorToErrno ();
2531 return error;
2532 }
2533
2534 return error;
2535}
2536
2537static Error
2538ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2539{
2540 memory_region_info.Clear();
2541
2542 StringExtractor line_extractor (maps_line.c_str ());
2543
2544 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2545 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2546
2547 // Parse out the starting address
2548 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2549
2550 // Parse out hyphen separating start and end address from range.
2551 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2552 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2553
2554 // Parse out the ending address
2555 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2556
2557 // Parse out the space after the address.
2558 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2559 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2560
2561 // Save the range.
2562 memory_region_info.GetRange ().SetRangeBase (start_address);
2563 memory_region_info.GetRange ().SetRangeEnd (end_address);
2564
2565 // Parse out each permission entry.
2566 if (line_extractor.GetBytesLeft () < 4)
2567 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2568
2569 // Handle read permission.
2570 const char read_perm_char = line_extractor.GetChar ();
2571 if (read_perm_char == 'r')
2572 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2573 else
2574 {
2575 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2576 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2577 }
2578
2579 // Handle write permission.
2580 const char write_perm_char = line_extractor.GetChar ();
2581 if (write_perm_char == 'w')
2582 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2583 else
2584 {
2585 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2586 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2587 }
2588
2589 // Handle execute permission.
2590 const char exec_perm_char = line_extractor.GetChar ();
2591 if (exec_perm_char == 'x')
2592 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2593 else
2594 {
2595 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2596 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2597 }
2598
2599 return Error ();
2600}
2601
2602Error
2603NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2604{
2605 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2606 // with no perms if it is not mapped.
2607
2608 // Use an approach that reads memory regions from /proc/{pid}/maps.
2609 // Assume proc maps entries are in ascending order.
2610 // FIXME assert if we find differently.
2611 Mutex::Locker locker (m_mem_region_cache_mutex);
2612
2613 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2614 Error error;
2615
2616 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2617 {
2618 // We're done.
2619 error.SetErrorString ("unsupported");
2620 return error;
2621 }
2622
2623 // If our cache is empty, pull the latest. There should always be at least one memory region
2624 // if memory region handling is supported.
2625 if (m_mem_region_cache.empty ())
2626 {
2627 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2628 [&] (const std::string &line) -> bool
2629 {
2630 MemoryRegionInfo info;
2631 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2632 if (parse_error.Success ())
2633 {
2634 m_mem_region_cache.push_back (info);
2635 return true;
2636 }
2637 else
2638 {
2639 if (log)
2640 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2641 return false;
2642 }
2643 });
2644
2645 // If we had an error, we'll mark unsupported.
2646 if (error.Fail ())
2647 {
2648 m_supports_mem_region = LazyBool::eLazyBoolNo;
2649 return error;
2650 }
2651 else if (m_mem_region_cache.empty ())
2652 {
2653 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2654 // is supported. Assume we don't support map entries via procfs.
2655 if (log)
2656 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2657 m_supports_mem_region = LazyBool::eLazyBoolNo;
2658 error.SetErrorString ("not supported");
2659 return error;
2660 }
2661
2662 if (log)
2663 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2664
2665 // We support memory retrieval, remember that.
2666 m_supports_mem_region = LazyBool::eLazyBoolYes;
2667 }
2668 else
2669 {
2670 if (log)
2671 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2672 }
2673
2674 lldb::addr_t prev_base_address = 0;
2675
2676 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2677 // There can be a ton of regions on pthreads apps with lots of threads.
2678 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2679 {
2680 MemoryRegionInfo &proc_entry_info = *it;
2681
2682 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2683 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2684 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2685
2686 // If the target address comes before this entry, indicate distance to next region.
2687 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2688 {
2689 range_info.GetRange ().SetRangeBase (load_addr);
2690 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2691 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2692 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2693 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2694
2695 return error;
2696 }
2697 else if (proc_entry_info.GetRange ().Contains (load_addr))
2698 {
2699 // The target address is within the memory region we're processing here.
2700 range_info = proc_entry_info;
2701 return error;
2702 }
2703
2704 // The target memory address comes somewhere after the region we just parsed.
2705 }
2706
Tamas Berghammer09839c32015-07-03 09:30:19 +00002707 // If we made it here, we didn't find an entry that contained the given address. Return the
2708 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2709 // size.
2710 range_info.GetRange ().SetRangeBase (load_addr);
2711 switch (m_arch.GetAddressByteSize())
2712 {
2713 case 4:
2714 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2715 break;
2716 case 8:
2717 range_info.GetRange ().SetByteSize (0ull - load_addr);
2718 break;
2719 default:
2720 assert(false && "Unrecognized data byte size");
2721 break;
2722 }
2723 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2724 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2725 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002726 return error;
2727}
2728
2729void
2730NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2731{
2732 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2733 if (log)
2734 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2735
2736 {
2737 Mutex::Locker locker (m_mem_region_cache_mutex);
2738 if (log)
2739 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2740 m_mem_region_cache.clear ();
2741 }
2742}
2743
2744Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002745NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002746{
2747 // FIXME implementing this requires the equivalent of
2748 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2749 // functional ThreadPlans working with Native*Protocol.
2750#if 1
2751 return Error ("not implemented yet");
2752#else
2753 addr = LLDB_INVALID_ADDRESS;
2754
2755 unsigned prot = 0;
2756 if (permissions & lldb::ePermissionsReadable)
2757 prot |= eMmapProtRead;
2758 if (permissions & lldb::ePermissionsWritable)
2759 prot |= eMmapProtWrite;
2760 if (permissions & lldb::ePermissionsExecutable)
2761 prot |= eMmapProtExec;
2762
2763 // TODO implement this directly in NativeProcessLinux
2764 // (and lift to NativeProcessPOSIX if/when that class is
2765 // refactored out).
2766 if (InferiorCallMmap(this, addr, 0, size, prot,
2767 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2768 m_addr_to_mmap_size[addr] = size;
2769 return Error ();
2770 } else {
2771 addr = LLDB_INVALID_ADDRESS;
2772 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2773 }
2774#endif
2775}
2776
2777Error
2778NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2779{
2780 // FIXME see comments in AllocateMemory - required lower-level
2781 // bits not in place yet (ThreadPlans)
2782 return Error ("not implemented");
2783}
2784
2785lldb::addr_t
2786NativeProcessLinux::GetSharedLibraryInfoAddress ()
2787{
2788#if 1
2789 // punt on this for now
2790 return LLDB_INVALID_ADDRESS;
2791#else
2792 // Return the image info address for the exe module
2793#if 1
2794 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2795
2796 ModuleSP module_sp;
2797 Error error = GetExeModuleSP (module_sp);
2798 if (error.Fail ())
2799 {
2800 if (log)
2801 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2802 return LLDB_INVALID_ADDRESS;
2803 }
2804
2805 if (module_sp == nullptr)
2806 {
2807 if (log)
2808 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2809 return LLDB_INVALID_ADDRESS;
2810 }
2811
2812 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2813 if (object_file_sp == nullptr)
2814 {
2815 if (log)
2816 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2817 return LLDB_INVALID_ADDRESS;
2818 }
2819
2820 return obj_file_sp->GetImageInfoAddress();
2821#else
2822 Target *target = &GetTarget();
2823 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2824 Address addr = obj_file->GetImageInfoAddress(target);
2825
2826 if (addr.IsValid())
2827 return addr.GetLoadAddress(target);
2828 return LLDB_INVALID_ADDRESS;
2829#endif
2830#endif // punt on this for now
2831}
2832
2833size_t
2834NativeProcessLinux::UpdateThreads ()
2835{
2836 // The NativeProcessLinux monitoring threads are always up to date
2837 // with respect to thread state and they keep the thread list
2838 // populated properly. All this method needs to do is return the
2839 // thread count.
2840 Mutex::Locker locker (m_threads_mutex);
2841 return m_threads.size ();
2842}
2843
2844bool
2845NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2846{
2847 arch = m_arch;
2848 return true;
2849}
2850
2851Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002852NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002853{
2854 // FIXME put this behind a breakpoint protocol class that can be
2855 // set per architecture. Need ARM, MIPS support here.
2856 static const uint8_t g_i386_opcode [] = { 0xCC };
2857
2858 switch (m_arch.GetMachine ())
2859 {
2860 case llvm::Triple::x86:
2861 case llvm::Triple::x86_64:
2862 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2863 return Error ();
2864
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002865 case llvm::Triple::arm:
2866 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002867 case llvm::Triple::mips64:
2868 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002869 case llvm::Triple::mips:
2870 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002871 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002872 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002873 return Error ();
2874
Todd Fialaaf245d12014-06-30 21:05:18 +00002875 default:
2876 assert(false && "CPU type not supported!");
2877 return Error ("CPU type not supported");
2878 }
2879}
2880
2881Error
2882NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2883{
2884 if (hardware)
2885 return Error ("NativeProcessLinux does not support hardware breakpoints");
2886 else
2887 return SetSoftwareBreakpoint (addr, size);
2888}
2889
2890Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002891NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2892 size_t &actual_opcode_size,
2893 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002894{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002895 // FIXME put this behind a breakpoint protocol class that can be set per
2896 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002897 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002898 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2899 // linux kernel does otherwise.
2900 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002901 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002902 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002903 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002904 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002905
2906 switch (m_arch.GetMachine ())
2907 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002908 case llvm::Triple::aarch64:
2909 trap_opcode_bytes = g_aarch64_opcode;
2910 actual_opcode_size = sizeof(g_aarch64_opcode);
2911 return Error ();
2912
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002913 case llvm::Triple::arm:
2914 switch (trap_opcode_size_hint)
2915 {
2916 case 2:
2917 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2918 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2919 return Error ();
2920 case 4:
2921 trap_opcode_bytes = g_arm_breakpoint_opcode;
2922 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2923 return Error ();
2924 default:
2925 assert(false && "Unrecognised trap opcode size hint!");
2926 return Error ("Unrecognised trap opcode size hint!");
2927 }
2928
Todd Fialaaf245d12014-06-30 21:05:18 +00002929 case llvm::Triple::x86:
2930 case llvm::Triple::x86_64:
2931 trap_opcode_bytes = g_i386_opcode;
2932 actual_opcode_size = sizeof(g_i386_opcode);
2933 return Error ();
2934
Sagar Thakurce815e42015-06-03 10:14:24 +00002935 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002936 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002937 trap_opcode_bytes = g_mips64_opcode;
2938 actual_opcode_size = sizeof(g_mips64_opcode);
2939 return Error ();
2940
Sagar Thakurce815e42015-06-03 10:14:24 +00002941 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002942 case llvm::Triple::mips64el:
2943 trap_opcode_bytes = g_mips64el_opcode;
2944 actual_opcode_size = sizeof(g_mips64el_opcode);
2945 return Error ();
2946
Todd Fialaaf245d12014-06-30 21:05:18 +00002947 default:
2948 assert(false && "CPU type not supported!");
2949 return Error ("CPU type not supported");
2950 }
2951}
2952
2953#if 0
2954ProcessMessage::CrashReason
2955NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2956{
2957 ProcessMessage::CrashReason reason;
2958 assert(info->si_signo == SIGSEGV);
2959
2960 reason = ProcessMessage::eInvalidCrashReason;
2961
2962 switch (info->si_code)
2963 {
2964 default:
2965 assert(false && "unexpected si_code for SIGSEGV");
2966 break;
2967 case SI_KERNEL:
2968 // Linux will occasionally send spurious SI_KERNEL codes.
2969 // (this is poorly documented in sigaction)
2970 // One way to get this is via unaligned SIMD loads.
2971 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2972 break;
2973 case SEGV_MAPERR:
2974 reason = ProcessMessage::eInvalidAddress;
2975 break;
2976 case SEGV_ACCERR:
2977 reason = ProcessMessage::ePrivilegedAddress;
2978 break;
2979 }
2980
2981 return reason;
2982}
2983#endif
2984
2985
2986#if 0
2987ProcessMessage::CrashReason
2988NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2989{
2990 ProcessMessage::CrashReason reason;
2991 assert(info->si_signo == SIGILL);
2992
2993 reason = ProcessMessage::eInvalidCrashReason;
2994
2995 switch (info->si_code)
2996 {
2997 default:
2998 assert(false && "unexpected si_code for SIGILL");
2999 break;
3000 case ILL_ILLOPC:
3001 reason = ProcessMessage::eIllegalOpcode;
3002 break;
3003 case ILL_ILLOPN:
3004 reason = ProcessMessage::eIllegalOperand;
3005 break;
3006 case ILL_ILLADR:
3007 reason = ProcessMessage::eIllegalAddressingMode;
3008 break;
3009 case ILL_ILLTRP:
3010 reason = ProcessMessage::eIllegalTrap;
3011 break;
3012 case ILL_PRVOPC:
3013 reason = ProcessMessage::ePrivilegedOpcode;
3014 break;
3015 case ILL_PRVREG:
3016 reason = ProcessMessage::ePrivilegedRegister;
3017 break;
3018 case ILL_COPROC:
3019 reason = ProcessMessage::eCoprocessorError;
3020 break;
3021 case ILL_BADSTK:
3022 reason = ProcessMessage::eInternalStackError;
3023 break;
3024 }
3025
3026 return reason;
3027}
3028#endif
3029
3030#if 0
3031ProcessMessage::CrashReason
3032NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3033{
3034 ProcessMessage::CrashReason reason;
3035 assert(info->si_signo == SIGFPE);
3036
3037 reason = ProcessMessage::eInvalidCrashReason;
3038
3039 switch (info->si_code)
3040 {
3041 default:
3042 assert(false && "unexpected si_code for SIGFPE");
3043 break;
3044 case FPE_INTDIV:
3045 reason = ProcessMessage::eIntegerDivideByZero;
3046 break;
3047 case FPE_INTOVF:
3048 reason = ProcessMessage::eIntegerOverflow;
3049 break;
3050 case FPE_FLTDIV:
3051 reason = ProcessMessage::eFloatDivideByZero;
3052 break;
3053 case FPE_FLTOVF:
3054 reason = ProcessMessage::eFloatOverflow;
3055 break;
3056 case FPE_FLTUND:
3057 reason = ProcessMessage::eFloatUnderflow;
3058 break;
3059 case FPE_FLTRES:
3060 reason = ProcessMessage::eFloatInexactResult;
3061 break;
3062 case FPE_FLTINV:
3063 reason = ProcessMessage::eFloatInvalidOperation;
3064 break;
3065 case FPE_FLTSUB:
3066 reason = ProcessMessage::eFloatSubscriptRange;
3067 break;
3068 }
3069
3070 return reason;
3071}
3072#endif
3073
3074#if 0
3075ProcessMessage::CrashReason
3076NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3077{
3078 ProcessMessage::CrashReason reason;
3079 assert(info->si_signo == SIGBUS);
3080
3081 reason = ProcessMessage::eInvalidCrashReason;
3082
3083 switch (info->si_code)
3084 {
3085 default:
3086 assert(false && "unexpected si_code for SIGBUS");
3087 break;
3088 case BUS_ADRALN:
3089 reason = ProcessMessage::eIllegalAlignment;
3090 break;
3091 case BUS_ADRERR:
3092 reason = ProcessMessage::eIllegalAddress;
3093 break;
3094 case BUS_OBJERR:
3095 reason = ProcessMessage::eHardwareError;
3096 break;
3097 }
3098
3099 return reason;
3100}
3101#endif
3102
Todd Fialaaf245d12014-06-30 21:05:18 +00003103Error
Pavel Labath5abe7262015-07-16 08:45:03 +00003104NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3105{
3106 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3107 // for it.
3108 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3109 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3110}
3111
3112Error
3113NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3114{
3115 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3116 // for it.
3117 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3118 return NativeProcessProtocol::RemoveWatchpoint(addr);
3119}
3120
3121Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003122NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003123{
Pavel Labathdf7c6992015-06-17 18:38:49 +00003124 if (ProcessVmReadvSupported()) {
3125 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3126 // this syscall if it is supported.
3127
3128 const ::pid_t pid = GetID();
3129
3130 struct iovec local_iov, remote_iov;
3131 local_iov.iov_base = buf;
3132 local_iov.iov_len = size;
3133 remote_iov.iov_base = reinterpret_cast<void *>(addr);
3134 remote_iov.iov_len = size;
3135
3136 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3137 const bool success = bytes_read == size;
3138
3139 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3140 if (log)
3141 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3142 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3143
3144 if (success)
3145 return Error();
3146 // else
3147 // the call failed for some reason, let's retry the read using ptrace api.
3148 }
3149
Pavel Labath5abe7262015-07-16 08:45:03 +00003150 return DoOperation([&] { return DoReadMemory(GetID(), addr, buf, size, bytes_read); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003151}
3152
3153Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003154NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3155{
3156 Error error = ReadMemory(addr, buf, size, bytes_read);
3157 if (error.Fail()) return error;
3158 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3159}
3160
3161Error
3162NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003163{
Pavel Labath5abe7262015-07-16 08:45:03 +00003164 return DoOperation([&] { return DoWriteMemory(GetID(), addr, buf, size, bytes_written); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003165}
3166
Chaoren Lin97ccc292015-02-03 01:51:12 +00003167Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003168NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3169{
Todd Fialaaf245d12014-06-30 21:05:18 +00003170 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3171
3172 if (log)
3173 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003174 Host::GetSignalAsCString(signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00003175
3176
3177
3178 intptr_t data = 0;
3179
3180 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3181 data = signo;
3182
Pavel Labath5abe7262015-07-16 08:45:03 +00003183 Error error = DoOperation([&] { return PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data); });
Pavel Labathc7512fd2015-06-26 10:14:12 +00003184
Todd Fialaaf245d12014-06-30 21:05:18 +00003185 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00003186 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
3187 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00003188}
3189
Chaoren Lin97ccc292015-02-03 01:51:12 +00003190Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003191NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3192{
Pavel Labathc7512fd2015-06-26 10:14:12 +00003193 intptr_t data = 0;
3194
3195 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3196 data = signo;
3197
Pavel Labath5abe7262015-07-16 08:45:03 +00003198 return DoOperation([&] { return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003199}
3200
Chaoren Lin97ccc292015-02-03 01:51:12 +00003201Error
3202NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003203{
Pavel Labath5abe7262015-07-16 08:45:03 +00003204 return DoOperation([&] { return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003205}
3206
Chaoren Lin97ccc292015-02-03 01:51:12 +00003207Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003208NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3209{
Pavel Labath5abe7262015-07-16 08:45:03 +00003210 return DoOperation([&] { return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003211}
3212
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003213Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003214NativeProcessLinux::Detach(lldb::tid_t tid)
3215{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003216 if (tid == LLDB_INVALID_THREAD_ID)
3217 return Error();
3218
Pavel Labath5abe7262015-07-16 08:45:03 +00003219 return DoOperation([&] { return PtraceWrapper(PTRACE_DETACH, tid); });
Todd Fialaaf245d12014-06-30 21:05:18 +00003220}
3221
3222bool
Chaoren Lind3173f32015-05-29 19:52:29 +00003223NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00003224{
Chaoren Lind3173f32015-05-29 19:52:29 +00003225 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00003226
3227 if (target_fd == -1)
3228 return false;
3229
Pavel Labath493c3a12015-02-04 10:36:57 +00003230 if (dup2(target_fd, fd) == -1)
3231 return false;
3232
3233 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003234}
3235
Pavel Labath5abe7262015-07-16 08:45:03 +00003236void
3237NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3238{
3239 m_monitor_up.reset(new Monitor(initial_operation, this));
3240 error = m_monitor_up->Initialize();
3241 if (error.Fail()) {
3242 m_monitor_up.reset();
3243 }
3244}
3245
Todd Fialaaf245d12014-06-30 21:05:18 +00003246bool
3247NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3248{
3249 for (auto thread_sp : m_threads)
3250 {
3251 assert (thread_sp && "thread list should not contain NULL threads");
3252 if (thread_sp->GetID () == thread_id)
3253 {
3254 // We have this thread.
3255 return true;
3256 }
3257 }
3258
3259 // We don't have this thread.
3260 return false;
3261}
3262
3263NativeThreadProtocolSP
3264NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3265{
3266 // CONSIDER organize threads by map - we can do better than linear.
3267 for (auto thread_sp : m_threads)
3268 {
3269 if (thread_sp->GetID () == thread_id)
3270 return thread_sp;
3271 }
3272
3273 // We don't have this thread.
3274 return NativeThreadProtocolSP ();
3275}
3276
3277bool
3278NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3279{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003280 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3281
3282 if (log)
3283 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3284
3285 bool found = false;
3286
Todd Fialaaf245d12014-06-30 21:05:18 +00003287 Mutex::Locker locker (m_threads_mutex);
3288 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3289 {
3290 if (*it && ((*it)->GetID () == thread_id))
3291 {
3292 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003293 found = true;
3294 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003295 }
3296 }
3297
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003298 // If we have a pending notification, remove this from the set.
3299 if (m_pending_notification_up)
3300 {
3301 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003302 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003303 }
3304
3305 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003306}
3307
3308NativeThreadProtocolSP
3309NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3310{
3311 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3312
3313 Mutex::Locker locker (m_threads_mutex);
3314
3315 if (log)
3316 {
3317 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3318 __FUNCTION__,
3319 GetID (),
3320 thread_id);
3321 }
3322
3323 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3324
3325 // If this is the first thread, save it as the current thread
3326 if (m_threads.empty ())
3327 SetCurrentThreadID (thread_id);
3328
3329 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3330 m_threads.push_back (thread_sp);
3331
3332 return thread_sp;
3333}
3334
Todd Fialaaf245d12014-06-30 21:05:18 +00003335Error
3336NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3337{
Todd Fiala75f47c32014-10-11 21:42:09 +00003338 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003339
3340 Error error;
3341
3342 // Get a linux thread pointer.
3343 if (!thread_sp)
3344 {
3345 error.SetErrorString ("null thread_sp");
3346 if (log)
3347 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3348 return error;
3349 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003350 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003351
3352 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003353 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003354 if (!context_sp)
3355 {
3356 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3357 if (log)
3358 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3359 return error;
3360 }
3361
3362 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003363 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003364 if (error.Fail ())
3365 {
3366 if (log)
3367 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3368 return error;
3369 }
3370 else
3371 {
3372 if (log)
3373 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3374 }
3375
3376 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00003377 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003378 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003379 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003380 {
3381 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003382 if (breakpoint_addr >= breakpoint_size)
3383 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003384 }
3385
3386 // Check if we stopped because of a breakpoint.
3387 NativeBreakpointSP breakpoint_sp;
3388 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3389 if (!error.Success () || !breakpoint_sp)
3390 {
3391 // We didn't find one at a software probe location. Nothing to do.
3392 if (log)
3393 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3394 return Error ();
3395 }
3396
3397 // If the breakpoint is not a software breakpoint, nothing to do.
3398 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3399 {
3400 if (log)
3401 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3402 return Error ();
3403 }
3404
3405 //
3406 // We have a software breakpoint and need to adjust the PC.
3407 //
3408
3409 // Sanity check.
3410 if (breakpoint_size == 0)
3411 {
3412 // Nothing to do! How did we get here?
3413 if (log)
3414 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);
3415 return Error ();
3416 }
3417
3418 // Change the program counter.
3419 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003420 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 +00003421
3422 error = context_sp->SetPC (breakpoint_addr);
3423 if (error.Fail ())
3424 {
3425 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003426 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 +00003427 return error;
3428 }
3429
3430 return error;
3431}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003432
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003433Error
3434NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3435{
3436 char maps_file_name[32];
3437 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3438
3439 FileSpec maps_file_spec(maps_file_name, false);
3440 if (!maps_file_spec.Exists()) {
3441 file_spec.Clear();
3442 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3443 }
3444
3445 FileSpec module_file_spec(module_path, true);
3446
3447 std::ifstream maps_file(maps_file_name);
3448 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3449 StringRef maps_data(maps_data_str.c_str());
3450
3451 while (!maps_data.empty())
3452 {
3453 StringRef maps_row;
3454 std::tie(maps_row, maps_data) = maps_data.split('\n');
3455
3456 SmallVector<StringRef, 16> maps_columns;
3457 maps_row.split(maps_columns, StringRef(" "), -1, false);
3458
3459 if (maps_columns.size() >= 6)
3460 {
3461 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3462 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3463 return Error();
3464 }
3465 }
3466
3467 file_spec.Clear();
3468 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3469 module_file_spec.GetFilename().AsCString(), GetID());
3470}
Pavel Labathc0765592015-05-06 10:46:34 +00003471
Pavel Labath5eb721e2015-05-07 08:30:31 +00003472Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003473NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3474{
3475 load_addr = LLDB_INVALID_ADDRESS;
3476 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3477 [&] (const std::string &line) -> bool
3478 {
3479 StringRef maps_row(line);
3480
3481 SmallVector<StringRef, 16> maps_columns;
3482 maps_row.split(maps_columns, StringRef(" "), -1, false);
3483
3484 if (maps_columns.size() < 6)
3485 {
3486 // Return true to continue reading the proc file
3487 return true;
3488 }
3489
3490 if (maps_columns[5] == file_name)
3491 {
3492 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3493 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3494
3495 // Return false to stop reading the proc file further
3496 return false;
3497 }
3498
3499 // Return true to continue reading the proc file
3500 return true;
3501 });
3502 return error;
3503}
3504
3505Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003506NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003507 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003508 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003509 bool error_when_already_running)
3510{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003511 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003512
3513 if (log)
3514 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3515 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003516
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003517 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3518 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003519
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003520 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003521 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003522 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003523
3524 lldbassert(!(error_when_already_running && !is_stopped));
3525
Pavel Labathc0765592015-05-06 10:46:34 +00003526 if (!is_stopped)
3527 {
3528 // It's not an error, just a log, if the error_when_already_running flag is not set.
3529 // This covers cases where, for instance, we're just trying to resume all threads
3530 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003531 if (log)
3532 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3533 __FUNCTION__,
3534 tid);
3535 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003536 }
3537
3538 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003539 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003540 // this thread to stop. This is potentially a buggy situation since
3541 // we're ostensibly waiting for threads to stop before we send out the
3542 // pending notification, and here we are resuming one before we send
3543 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003544 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003545 {
Pavel Labath108c3252015-05-12 09:03:18 +00003546 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 +00003547 }
3548
3549 // Request a resume. We expect this to be synchronous and the system
3550 // to reflect it is running after this completes.
3551 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003552 if (error.Success())
3553 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003554 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003555 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003556 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003557 __FUNCTION__, tid, error.AsCString ());
3558 }
3559
Pavel Labath5eb721e2015-05-07 08:30:31 +00003560 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003561}
3562
3563//===----------------------------------------------------------------------===//
3564
3565void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003566NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003567{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003568 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003569
Pavel Labath5eb721e2015-05-07 08:30:31 +00003570 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003571 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003572 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003573 __FUNCTION__, triggering_tid);
3574 }
3575
Pavel Labath337f3eb2015-05-08 08:57:45 +00003576 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003577
Pavel Labath5eb721e2015-05-07 08:30:31 +00003578 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003579 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003580 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003581 }
3582}
3583
3584void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003585NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003586{
3587 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3588 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003589 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3590
3591 // Clear any temporary breakpoints we used to implement software single stepping.
3592 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3593 {
3594 Error error = RemoveBreakpoint (thread_info.second);
3595 if (error.Fail())
3596 if (log)
3597 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3598 __FUNCTION__, thread_info.first, error.AsCString());
3599 }
3600 m_threads_stepping_with_breakpoint.clear();
3601
3602 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003603 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3604 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003605 m_pending_notification_up.reset();
3606 }
3607}
3608
Pavel Labathc0765592015-05-06 10:46:34 +00003609void
3610NativeProcessLinux::RequestStopOnAllRunningThreads()
3611{
3612 // Request a stop for all the thread stops that need to be stopped
3613 // and are not already known to be stopped. Keep a list of all the
3614 // threads from which we still need to hear a stop reply.
3615
3616 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003617 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003618 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003619 // We only care about running threads
3620 if (StateIsStoppedState(thread_sp->GetState(), true))
3621 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003622
Pavel Labath108c3252015-05-12 09:03:18 +00003623 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3624 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003625 }
3626
3627 // Set the wait list to the set of tids for which we requested stops.
3628 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3629}
3630
Pavel Labathc0765592015-05-06 10:46:34 +00003631
Pavel Labath5eb721e2015-05-07 08:30:31 +00003632Error
3633NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003634{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003635 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3636
3637 if (log)
3638 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3639 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3640
Pavel Labathc0765592015-05-06 10:46:34 +00003641 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003642 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3643 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003644
3645 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003646 auto& context = thread_sp->GetThreadContext();
3647 const auto stop_was_requested = context.stop_requested;
3648 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003649
3650 // If we have a pending notification, remove this from the set.
3651 if (m_pending_notification_up)
3652 {
3653 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003654 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003655 }
3656
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003657 Error error;
3658 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003659 {
3660 // We can end up here if stop was initiated by LLGS but by this time a
3661 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003662 if (log)
3663 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003664 error = context.request_resume_function (tid, true);
3665 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003666 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003667 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3668 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003669 }
3670 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003671 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003672}
3673
3674void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003675NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003676{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003677 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3678 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003679 {
3680 // Yikes - we've already got a pending signal notification in progress.
3681 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003682 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 +00003683 __FUNCTION__,
3684 m_pending_notification_up->triggering_tid,
3685 notification_up->triggering_tid);
3686 }
3687 m_pending_notification_up = std::move(notification_up);
3688
Pavel Labath108c3252015-05-12 09:03:18 +00003689 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003690
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003691 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003692}
3693
3694void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003695NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003696{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003697 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3698
3699 if (log)
3700 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3701
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003702 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3703 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003704
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003705 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003706 {
3707 // We will need to wait for this new thread to stop as well before firing the
3708 // notification.
3709 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003710 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003711 }
3712}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003713
Pavel Labath5abe7262015-07-16 08:45:03 +00003714Error
3715NativeProcessLinux::DoOperation(const Operation &op)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003716{
Pavel Labath5abe7262015-07-16 08:45:03 +00003717 return m_monitor_up->DoOperation(op);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003718}
3719
3720// Wrapper for ptrace to catch errors and log calls.
3721// 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 +00003722Error
3723NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003724{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003725 Error error;
3726 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003727
3728 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3729
3730 PtraceDisplayBytes(req, data, data_size);
3731
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003732 errno = 0;
3733 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003734 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003735 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003736 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003737
Pavel Labath4a9babb2015-06-30 17:04:49 +00003738 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003739 error.SetErrorToErrno();
3740
Pavel Labath4a9babb2015-06-30 17:04:49 +00003741 if (result)
3742 *result = ret;
3743
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003744 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003745 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003746
3747 PtraceDisplayBytes(req, data, data_size);
3748
3749 if (log && error.GetError() != 0)
3750 {
3751 const char* str;
3752 switch (error.GetError())
3753 {
3754 case ESRCH: str = "ESRCH"; break;
3755 case EINVAL: str = "EINVAL"; break;
3756 case EBUSY: str = "EBUSY"; break;
3757 case EPERM: str = "EPERM"; break;
3758 default: str = error.AsCString();
3759 }
3760 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3761 }
3762
Pavel Labath4a9babb2015-06-30 17:04:49 +00003763 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003764}