blob: ec286b055c4b472c16ae25963a4d622316b030a7 [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
10#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
21// C++ Includes
22#include <fstream>
Pavel Labathc0765592015-05-06 10:46:34 +000023#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000024#include <string>
25
26// Other libraries and framework includes
27#include "lldb/Core/Debugger.h"
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000028#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/Error.h"
30#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000031#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000032#include "lldb/Core/RegisterValue.h"
33#include "lldb/Core/Scalar.h"
34#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000035#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000036#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000037#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000038#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000039#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000042#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000044#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "lldb/Utility/PseudoTerminal.h"
46
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000048#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000049#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
51#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054// System includes - They have to be included after framework includes because they define some
55// macros which collide with variable names in other modules
56#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000058
Tamas Berghammerd8584872015-02-06 10:57:40 +000059#include <sys/types.h>
60#include <sys/uio.h>
61#include <sys/user.h>
62#include <sys/wait.h>
63
Vince Harron8b335672015-05-12 01:10:56 +000064#include "lldb/Host/linux/Personality.h"
65#include "lldb/Host/linux/Ptrace.h"
66#include "lldb/Host/linux/Signalfd.h"
67#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000068
Todd Fiala0bce1b62014-08-17 00:10:50 +000069#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000070
71// Support hardware breakpoints in case it has not been defined
72#ifndef TRAP_HWBKPT
73 #define TRAP_HWBKPT 4
74#endif
75
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000076using namespace lldb;
77using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000078using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000079using namespace llvm;
80
Todd Fialaaf245d12014-06-30 21:05:18 +000081// Private bits we only need internally.
82namespace
83{
Todd Fialaaf245d12014-06-30 21:05:18 +000084 const UnixSignals&
85 GetUnixSignals ()
86 {
87 static process_linux::LinuxSignals signals;
88 return signals;
89 }
90
Todd Fialaaf245d12014-06-30 21:05:18 +000091 Error
92 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
93 {
94 // Grab process info for the running process.
95 ProcessInstanceInfo process_info;
96 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +000097 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +000098
99 // Resolve the executable module.
100 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000101 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000102 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
103 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000104 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000105 exe_module_sp,
106 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
107
108 if (!error.Success ())
109 return error;
110
111 // Check if we've got our architecture from the exe_module.
112 arch = exe_module_sp->GetArchitecture ();
113 if (arch.IsValid ())
114 return Error();
115 else
116 return Error("failed to retrieve a valid architecture from the exe module");
117 }
118
119 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000120 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000121 {
122 uint8_t *ptr = (uint8_t *)bytes;
123 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
124 for(uint32_t i=0; i<loop_count; i++)
125 {
126 s.Printf ("[%x]", *ptr);
127 ptr++;
128 }
129 }
130
131 void
132 PtraceDisplayBytes(int &req, void *data, size_t data_size)
133 {
134 StreamString buf;
135 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
136 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
137
138 if (verbose_log)
139 {
140 switch(req)
141 {
142 case PTRACE_POKETEXT:
143 {
144 DisplayBytes(buf, &data, 8);
145 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
146 break;
147 }
148 case PTRACE_POKEDATA:
149 {
150 DisplayBytes(buf, &data, 8);
151 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
152 break;
153 }
154 case PTRACE_POKEUSER:
155 {
156 DisplayBytes(buf, &data, 8);
157 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
158 break;
159 }
160 case PTRACE_SETREGS:
161 {
162 DisplayBytes(buf, data, data_size);
163 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
164 break;
165 }
166 case PTRACE_SETFPREGS:
167 {
168 DisplayBytes(buf, data, data_size);
169 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
170 break;
171 }
172 case PTRACE_SETSIGINFO:
173 {
174 DisplayBytes(buf, data, sizeof(siginfo_t));
175 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
176 break;
177 }
178 case PTRACE_SETREGSET:
179 {
180 // Extract iov_base from data, which is a pointer to the struct IOVEC
181 DisplayBytes(buf, *(void **)data, data_size);
182 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
183 break;
184 }
185 default:
186 {
187 }
188 }
189 }
190 }
191
Todd Fialaaf245d12014-06-30 21:05:18 +0000192 //------------------------------------------------------------------------------
193 // Static implementations of NativeProcessLinux::ReadMemory and
194 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
195 // functions without needed to go thru the thread funnel.
196
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000197 size_t
198 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000199 lldb::pid_t pid,
200 lldb::addr_t vm_addr,
201 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000202 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000203 Error &error)
204 {
205 // ptrace word size is determined by the host, not the child
206 static const unsigned word_size = sizeof(void*);
207 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000208 size_t bytes_read;
209 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000210 long data;
211
212 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
213 if (log)
214 ProcessPOSIXLog::IncNestLevel();
215 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
216 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
217 pid, word_size, (void*)vm_addr, buf, size);
218
219 assert(sizeof(data) >= word_size);
220 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
221 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000222 data = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000223 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000224 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000225 if (log)
226 ProcessPOSIXLog::DecNestLevel();
227 return bytes_read;
228 }
229
230 remainder = size - bytes_read;
231 remainder = remainder > word_size ? word_size : remainder;
232
233 // Copy the data into our buffer
234 for (unsigned i = 0; i < remainder; ++i)
235 dst[i] = ((data >> i*8) & 0xFF);
236
237 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
238 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
239 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
240 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
241 {
242 uintptr_t print_dst = 0;
243 // Format bytes from data by moving into print_dst for log output
244 for (unsigned i = 0; i < remainder; ++i)
245 print_dst |= (((data >> i*8) & 0xFF) << i*8);
246 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
247 (void*)vm_addr, print_dst, (unsigned long)data);
248 }
249
250 vm_addr += word_size;
251 dst += word_size;
252 }
253
254 if (log)
255 ProcessPOSIXLog::DecNestLevel();
256 return bytes_read;
257 }
258
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000259 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000260 DoWriteMemory(
261 lldb::pid_t pid,
262 lldb::addr_t vm_addr,
263 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000264 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000265 Error &error)
266 {
267 // ptrace word size is determined by the host, not the child
268 static const unsigned word_size = sizeof(void*);
269 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000270 size_t bytes_written = 0;
271 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000272
273 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
274 if (log)
275 ProcessPOSIXLog::IncNestLevel();
276 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
277 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
278 pid, word_size, (void*)vm_addr, buf, size);
279
280 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
281 {
282 remainder = size - bytes_written;
283 remainder = remainder > word_size ? word_size : remainder;
284
285 if (remainder == word_size)
286 {
287 unsigned long data = 0;
288 assert(sizeof(data) >= word_size);
289 for (unsigned i = 0; i < word_size; ++i)
290 data |= (unsigned long)src[i] << i*8;
291
292 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
293 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
294 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
295 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
296 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000297 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000298
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000299 if (NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000300 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000301 if (log)
302 ProcessPOSIXLog::DecNestLevel();
303 return bytes_written;
304 }
305 }
306 else
307 {
308 unsigned char buff[8];
309 if (DoReadMemory(pid, vm_addr,
310 buff, word_size, error) != word_size)
311 {
312 if (log)
313 ProcessPOSIXLog::DecNestLevel();
314 return bytes_written;
315 }
316
317 memcpy(buff, src, remainder);
318
319 if (DoWriteMemory(pid, vm_addr,
320 buff, word_size, error) != word_size)
321 {
322 if (log)
323 ProcessPOSIXLog::DecNestLevel();
324 return bytes_written;
325 }
326
327 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
328 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
329 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
330 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
331 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000332 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000333 }
334
335 vm_addr += word_size;
336 src += word_size;
337 }
338 if (log)
339 ProcessPOSIXLog::DecNestLevel();
340 return bytes_written;
341 }
342
343 //------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000344 /// @class ReadOperation
345 /// @brief Implements NativeProcessLinux::ReadMemory.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000346 class ReadOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000347 {
348 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000349 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000350 lldb::addr_t addr,
351 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000352 size_t size,
353 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000354 Operation (),
355 m_addr (addr),
356 m_buff (buff),
357 m_size (size),
358 m_result (result)
359 {
360 }
361
362 void Execute (NativeProcessLinux *process) override;
363
364 private:
365 lldb::addr_t m_addr;
366 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000367 size_t m_size;
368 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000369 };
370
371 void
372 ReadOperation::Execute (NativeProcessLinux *process)
373 {
374 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
375 }
376
377 //------------------------------------------------------------------------------
378 /// @class WriteOperation
379 /// @brief Implements NativeProcessLinux::WriteMemory.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000380 class WriteOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000381 {
382 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000383 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000384 lldb::addr_t addr,
385 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000386 size_t size,
387 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000388 Operation (),
389 m_addr (addr),
390 m_buff (buff),
391 m_size (size),
392 m_result (result)
393 {
394 }
395
396 void Execute (NativeProcessLinux *process) override;
397
398 private:
399 lldb::addr_t m_addr;
400 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000401 size_t m_size;
402 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000403 };
404
405 void
406 WriteOperation::Execute(NativeProcessLinux *process)
407 {
408 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
409 }
410
411 //------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +0000412 /// @class ResumeOperation
413 /// @brief Implements NativeProcessLinux::Resume.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000414 class ResumeOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000415 {
416 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000417 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
418 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000419
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000420 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000421
422 private:
423 lldb::tid_t m_tid;
424 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000425 };
426
427 void
428 ResumeOperation::Execute(NativeProcessLinux *monitor)
429 {
430 intptr_t data = 0;
431
432 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
433 data = m_signo;
434
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000435 NativeProcessLinux::PtraceWrapper(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000436 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000437 {
438 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
439
440 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000441 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000442 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000443 }
444
445 //------------------------------------------------------------------------------
446 /// @class SingleStepOperation
447 /// @brief Implements NativeProcessLinux::SingleStep.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000448 class SingleStepOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000449 {
450 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000451 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
452 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000453
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000454 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000455
456 private:
457 lldb::tid_t m_tid;
458 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000459 };
460
461 void
462 SingleStepOperation::Execute(NativeProcessLinux *monitor)
463 {
464 intptr_t data = 0;
465
466 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
467 data = m_signo;
468
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000469 NativeProcessLinux::PtraceWrapper(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000470 }
471
472 //------------------------------------------------------------------------------
473 /// @class SiginfoOperation
474 /// @brief Implements NativeProcessLinux::GetSignalInfo.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000475 class SiginfoOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000476 {
477 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000478 SiginfoOperation(lldb::tid_t tid, void *info)
479 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000480
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000481 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000482
483 private:
484 lldb::tid_t m_tid;
485 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +0000486 };
487
488 void
489 SiginfoOperation::Execute(NativeProcessLinux *monitor)
490 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000491 NativeProcessLinux::PtraceWrapper(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000492 }
493
494 //------------------------------------------------------------------------------
495 /// @class EventMessageOperation
496 /// @brief Implements NativeProcessLinux::GetEventMessage.
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000497 class EventMessageOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000498 {
499 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000500 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
501 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000502
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000503 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000504
505 private:
506 lldb::tid_t m_tid;
507 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +0000508 };
509
510 void
511 EventMessageOperation::Execute(NativeProcessLinux *monitor)
512 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000513 NativeProcessLinux::PtraceWrapper(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000514 }
515
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000516 class DetachOperation : public NativeProcessLinux::Operation
Todd Fialaaf245d12014-06-30 21:05:18 +0000517 {
518 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000519 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000520
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000521 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000522
523 private:
524 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000525 };
526
527 void
528 DetachOperation::Execute(NativeProcessLinux *monitor)
529 {
Tamas Berghammer068f8a72015-05-26 11:58:52 +0000530 NativeProcessLinux::PtraceWrapper(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000531 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000532} // end of anonymous namespace
533
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000534// Simple helper function to ensure flags are enabled on the given file
535// descriptor.
536static Error
537EnsureFDFlags(int fd, int flags)
538{
539 Error error;
540
541 int status = fcntl(fd, F_GETFL);
542 if (status == -1)
543 {
544 error.SetErrorToErrno();
545 return error;
546 }
547
548 if (fcntl(fd, F_SETFL, status | flags) == -1)
549 {
550 error.SetErrorToErrno();
551 return error;
552 }
553
554 return error;
555}
556
557// This class encapsulates the privileged thread which performs all ptrace and wait operations on
558// the inferior. The thread consists of a main loop which waits for events and processes them
559// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
560// the inferior process. Upon receiving this signal we do a waitpid to get more information
561// and dispatch to NativeProcessLinux::MonitorCallback.
562// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
563// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
564// pipe, and the completion of the operation is signalled over the semaphore.
565// - thread exit event: this is signaled from the Monitor destructor by closing the write end
566// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000567class NativeProcessLinux::Monitor
568{
Pavel Labath1107b5a2015-04-17 14:07:49 +0000569private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000570 // The initial monitor operation (launch or attach). It returns a inferior process id.
571 std::unique_ptr<InitialOperation> m_initial_operation_up;
572
573 ::pid_t m_child_pid = -1;
574 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000575
576 enum { READ, WRITE };
577 int m_pipefd[2] = {-1, -1};
578 int m_signal_fd = -1;
579 HostThread m_thread;
580
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000581 // current operation which must be executed on the priviliged thread
582 Mutex m_operation_mutex;
583 Operation *m_operation = nullptr;
584 sem_t m_operation_sem;
585 Error m_operation_error;
586
Pavel Labath45f5cb32015-05-05 15:05:50 +0000587 unsigned m_operation_nesting_level = 0;
588
589 static constexpr char operation_command = 'o';
590 static constexpr char begin_block_command = '{';
591 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000592
Pavel Labath1107b5a2015-04-17 14:07:49 +0000593 void
594 HandleSignals();
595
596 void
597 HandleWait();
598
599 // Returns true if the thread should exit.
600 bool
601 HandleCommands();
602
603 void
604 MainLoop();
605
606 static void *
607 RunMonitor(void *arg);
608
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000609 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000610 WaitForAck();
611
612 void
613 BeginOperationBlock()
614 {
615 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
616 WaitForAck();
617 }
618
619 void
620 EndOperationBlock()
621 {
622 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
623 WaitForAck();
624 }
625
Pavel Labath1107b5a2015-04-17 14:07:49 +0000626public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000627 Monitor(const InitialOperation &initial_operation,
628 NativeProcessLinux *native_process)
629 : m_initial_operation_up(new InitialOperation(initial_operation)),
630 m_native_process(native_process)
631 {
632 sem_init(&m_operation_sem, 0, 0);
633 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000634
635 ~Monitor();
636
637 Error
638 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000639
640 void
Pavel Labath45f5cb32015-05-05 15:05:50 +0000641 Terminate();
642
643 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000644 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000645
646 class ScopedOperationLock {
647 Monitor &m_monitor;
648
649 public:
650 ScopedOperationLock(Monitor &monitor)
651 : m_monitor(monitor)
652 { m_monitor.BeginOperationBlock(); }
653
654 ~ScopedOperationLock()
655 { m_monitor.EndOperationBlock(); }
656 };
Pavel Labath1107b5a2015-04-17 14:07:49 +0000657};
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000658constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +0000659constexpr char NativeProcessLinux::Monitor::begin_block_command;
660constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000661
662Error
663NativeProcessLinux::Monitor::Initialize()
664{
665 Error error;
666
667 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
668 // listening for these signals over a signalfd file descriptors. This allows us to wait for
669 // multiple kinds of events with select.
670 sigset_t signals;
671 sigemptyset(&signals);
672 sigaddset(&signals, SIGCHLD);
673 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
674 if (m_signal_fd < 0)
675 {
676 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
677 __FUNCTION__, strerror(errno));
678
679 }
680
681 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
682 {
683 error.SetErrorToErrno();
684 return error;
685 }
686
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000687 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
688 return error;
689 }
690
691 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
692 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000693 if (!m_thread.IsJoinable())
694 return Error("Failed to create monitor thread for NativeProcessLinux.");
695
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000696 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +0000697 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000698}
699
700void
701NativeProcessLinux::Monitor::DoOperation(Operation *op)
702{
703 if (m_thread.EqualsThread(pthread_self())) {
704 // If we're on the Monitor thread, we can simply execute the operation.
705 op->Execute(m_native_process);
706 return;
707 }
708
709 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
710 Mutex::Locker lock(m_operation_mutex);
711
712 m_operation = op;
713
714 // notify the thread that an operation is ready to be processed
715 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
716
Pavel Labath45f5cb32015-05-05 15:05:50 +0000717 WaitForAck();
718}
719
720void
721NativeProcessLinux::Monitor::Terminate()
722{
723 if (m_pipefd[WRITE] >= 0)
724 {
725 close(m_pipefd[WRITE]);
726 m_pipefd[WRITE] = -1;
727 }
728 if (m_thread.IsJoinable())
729 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +0000730}
731
Pavel Labath1107b5a2015-04-17 14:07:49 +0000732NativeProcessLinux::Monitor::~Monitor()
733{
Pavel Labath45f5cb32015-05-05 15:05:50 +0000734 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +0000735 if (m_pipefd[READ] >= 0)
736 close(m_pipefd[READ]);
737 if (m_signal_fd >= 0)
738 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000739 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000740}
741
742void
743NativeProcessLinux::Monitor::HandleSignals()
744{
745 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
746
747 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
748 // all the information from waitpid(). We just need to read all the signals so that we can
749 // sleep next time we reach select().
750 while (true)
751 {
752 signalfd_siginfo info;
753 ssize_t size = read(m_signal_fd, &info, sizeof info);
754 if (size == -1)
755 {
756 if (errno == EAGAIN || errno == EWOULDBLOCK)
757 break; // We are done.
758 if (errno == EINTR)
759 continue;
760 if (log)
761 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
762 __FUNCTION__, strerror(errno));
763 break;
764 }
765 if (size != sizeof info)
766 {
767 // We got incomplete information structure. This should not happen, let's just log
768 // that.
769 if (log)
770 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
771 "structure size is %zd, read returned %zd bytes",
772 __FUNCTION__, sizeof info, size);
773 break;
774 }
775 if (log)
776 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
777 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
778 }
779}
780
781void
782NativeProcessLinux::Monitor::HandleWait()
783{
784 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
785 // Process all pending waitpid notifications.
786 while (true)
787 {
788 int status = -1;
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000789 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000790
791 if (wait_pid == 0)
792 break; // We are done.
793
794 if (wait_pid == -1)
795 {
796 if (errno == EINTR)
797 continue;
798
799 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000800 log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
801 __FUNCTION__, strerror(errno));
Pavel Labath1107b5a2015-04-17 14:07:49 +0000802 break;
803 }
804
805 bool exited = false;
806 int signal = 0;
807 int exit_status = 0;
808 const char *status_cstr = NULL;
809 if (WIFSTOPPED(status))
810 {
811 signal = WSTOPSIG(status);
812 status_cstr = "STOPPED";
813 }
814 else if (WIFEXITED(status))
815 {
816 exit_status = WEXITSTATUS(status);
817 status_cstr = "EXITED";
818 exited = true;
819 }
820 else if (WIFSIGNALED(status))
821 {
822 signal = WTERMSIG(status);
823 status_cstr = "SIGNALED";
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000824 if (wait_pid == m_child_pid) {
Pavel Labath1107b5a2015-04-17 14:07:49 +0000825 exited = true;
826 exit_status = -1;
827 }
828 }
829 else
830 status_cstr = "(\?\?\?)";
831
832 if (log)
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000833 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
Pavel Labath1107b5a2015-04-17 14:07:49 +0000834 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000835 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000836
837 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
838 }
839}
840
841bool
842NativeProcessLinux::Monitor::HandleCommands()
843{
844 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
845
846 while (true)
847 {
848 char command = 0;
849 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
850 if (size == -1)
851 {
852 if (errno == EAGAIN || errno == EWOULDBLOCK)
853 return false;
854 if (errno == EINTR)
855 continue;
856 if (log)
857 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
858 return true;
859 }
860 if (size == 0) // end of file - write end closed
861 {
862 if (log)
863 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000864 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000865 return true; // We are done.
866 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000867
868 switch (command)
869 {
870 case operation_command:
871 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000872 break;
873 case begin_block_command:
874 ++m_operation_nesting_level;
875 break;
876 case end_block_command:
877 assert(m_operation_nesting_level > 0);
878 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000879 break;
880 default:
881 if (log)
882 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
883 __FUNCTION__, command);
884 }
Pavel Labath45f5cb32015-05-05 15:05:50 +0000885
886 // notify calling thread that the command has been processed
887 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000888 }
889}
890
891void
892NativeProcessLinux::Monitor::MainLoop()
893{
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000894 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
895 m_initial_operation_up.reset();
Pavel Labath05a1f2a2015-05-28 08:59:21 +0000896 m_child_pid = child_pid;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000897 sem_post(&m_operation_sem);
898
Pavel Labath1107b5a2015-04-17 14:07:49 +0000899 while (true)
900 {
901 fd_set fds;
902 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +0000903 // Only process waitpid events if we are outside of an operation block. Any pending
904 // events will be processed after we leave the block.
905 if (m_operation_nesting_level == 0)
906 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +0000907 FD_SET(m_pipefd[READ], &fds);
908
909 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
910 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
911 if (r < 0)
912 {
913 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
914 if (log)
915 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
916 __FUNCTION__, strerror(errno));
917 return;
918 }
919
920 if (FD_ISSET(m_pipefd[READ], &fds))
921 {
922 if (HandleCommands())
923 return;
924 }
925
926 if (FD_ISSET(m_signal_fd, &fds))
927 {
928 HandleSignals();
929 HandleWait();
930 }
931 }
932}
933
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000934Error
Pavel Labath45f5cb32015-05-05 15:05:50 +0000935NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000936{
937 Error error;
938 while (sem_wait(&m_operation_sem) != 0)
939 {
940 if (errno == EINTR)
941 continue;
942
943 error.SetErrorToErrno();
944 return error;
945 }
946
947 return m_operation_error;
948}
949
Pavel Labath1107b5a2015-04-17 14:07:49 +0000950void *
951NativeProcessLinux::Monitor::RunMonitor(void *arg)
952{
953 static_cast<Monitor *>(arg)->MainLoop();
954 return nullptr;
955}
956
957
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000958NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000959 char const **argv,
960 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +0000961 const std::string &stdin_path,
962 const std::string &stdout_path,
963 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000964 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000965 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000966 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000967 m_argv(argv),
968 m_envp(envp),
969 m_stdin_path(stdin_path),
970 m_stdout_path(stdout_path),
971 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000972 m_working_dir(working_dir),
973 m_launch_info(launch_info)
974{
975}
Todd Fialaaf245d12014-06-30 21:05:18 +0000976
977NativeProcessLinux::LaunchArgs::~LaunchArgs()
978{ }
979
Todd Fialaaf245d12014-06-30 21:05:18 +0000980// -----------------------------------------------------------------------------
981// Public Static Methods
982// -----------------------------------------------------------------------------
983
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000984Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000985NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000986 Module *exe_module,
987 ProcessLaunchInfo &launch_info,
988 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +0000989 NativeProcessProtocolSP &native_process_sp)
990{
991 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
992
993 Error error;
994
995 // Verify the working directory is valid if one was specified.
996 const char* working_dir = launch_info.GetWorkingDirectory ();
997 if (working_dir)
998 {
999 FileSpec working_dir_fs (working_dir, true);
1000 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1001 {
1002 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1003 return error;
1004 }
1005 }
1006
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001007 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001008
1009 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001010 std::string stdin_path;
1011 std::string stdout_path;
1012 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001013
1014 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001015 if (file_action)
1016 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001017
1018 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001019 if (file_action)
1020 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001021
1022 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001023 if (file_action)
1024 stderr_path = file_action->GetPath ();
1025
1026 if (log)
1027 {
1028 if (!stdin_path.empty ())
1029 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1030 else
1031 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1032
1033 if (!stdout_path.empty ())
1034 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1035 else
1036 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1037
1038 if (!stderr_path.empty ())
1039 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1040 else
1041 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1042 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
1044 // Create the NativeProcessLinux in launch mode.
1045 native_process_sp.reset (new NativeProcessLinux ());
1046
1047 if (log)
1048 {
1049 int i = 0;
1050 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1051 {
1052 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1053 ++i;
1054 }
1055 }
1056
1057 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1058 {
1059 native_process_sp.reset ();
1060 error.SetErrorStringWithFormat ("failed to register the native delegate");
1061 return error;
1062 }
1063
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001064 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001065 exe_module,
1066 launch_info.GetArguments ().GetConstArgumentVector (),
1067 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1068 stdin_path,
1069 stdout_path,
1070 stderr_path,
1071 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001072 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001073 error);
1074
1075 if (error.Fail ())
1076 {
1077 native_process_sp.reset ();
1078 if (log)
1079 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1080 return error;
1081 }
1082
1083 launch_info.SetProcessID (native_process_sp->GetID ());
1084
1085 return error;
1086}
1087
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001088Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001089NativeProcessLinux::AttachToProcess (
1090 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001091 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001092 NativeProcessProtocolSP &native_process_sp)
1093{
1094 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1095 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1096 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1097
1098 // Grab the current platform architecture. This should be Linux,
1099 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001100 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001101 if (!platform_sp)
1102 return Error("failed to get a valid default platform");
1103
1104 // Retrieve the architecture for the running process.
1105 ArchSpec process_arch;
1106 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1107 if (!error.Success ())
1108 return error;
1109
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001110 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001111
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001112 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001113 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001114 error.SetErrorStringWithFormat ("failed to register the native delegate");
1115 return error;
1116 }
1117
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001118 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001119 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001120 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001121
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001122 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001123 return error;
1124}
1125
1126// -----------------------------------------------------------------------------
1127// Public Instance Methods
1128// -----------------------------------------------------------------------------
1129
1130NativeProcessLinux::NativeProcessLinux () :
1131 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1132 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001133 m_supports_mem_region (eLazyBoolCalculate),
1134 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00001135 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001136{
1137}
1138
1139//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001140// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1141// Refer to Monitor and Operation classes to see why this is necessary.
1142//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001143void
1144NativeProcessLinux::LaunchInferior (
1145 Module *module,
1146 const char *argv[],
1147 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001148 const std::string &stdin_path,
1149 const std::string &stdout_path,
1150 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001151 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001152 const ProcessLaunchInfo &launch_info,
1153 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001154{
1155 if (module)
1156 m_arch = module->GetArchitecture ();
1157
Chaoren Linfa03ad22015-02-03 01:50:42 +00001158 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001159
1160 std::unique_ptr<LaunchArgs> args(
1161 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001162 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001163 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001164 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001165
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001166 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001167 if (!error.Success ())
1168 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001169}
1170
1171void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001172NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001173{
1174 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1175 if (log)
1176 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1177
1178 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001179 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001180 if (!platform_sp)
1181 {
1182 if (log)
1183 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1184 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001185 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001186 }
1187
1188 // Gather info about the process.
1189 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001190 if (!platform_sp->GetProcessInfo (pid, process_info))
1191 {
1192 if (log)
1193 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1194 error.SetErrorString ("failed to get process info");
1195 return;
1196 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001197
1198 // Resolve the executable module
1199 ModuleSP exe_module_sp;
1200 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001201 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001202 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001203 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001204 if (!error.Success())
1205 return;
1206
1207 // Set the architecture to the exe architecture.
1208 m_arch = exe_module_sp->GetArchitecture();
1209 if (log)
1210 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1211
1212 m_pid = pid;
1213 SetState(eStateAttaching);
1214
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001215 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001216 if (!error.Success ())
1217 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001218}
1219
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001220void
1221NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001222{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001223 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001224}
1225
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001226::pid_t
1227NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001228{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001229 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001230
1231 const char **argv = args->m_argv;
1232 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001233 const char *working_dir = args->m_working_dir;
1234
1235 lldb_utility::PseudoTerminal terminal;
1236 const size_t err_len = 1024;
1237 char err_str[err_len];
1238 lldb::pid_t pid;
1239 NativeThreadProtocolSP thread_sp;
1240
1241 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001242
1243 // Propagate the environment if one is not supplied.
1244 if (envp == NULL || envp[0] == NULL)
1245 envp = const_cast<const char **>(environ);
1246
1247 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1248 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001249 error.SetErrorToGenericError();
1250 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1251 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001252 }
1253
1254 // Recognized child exit status codes.
1255 enum {
1256 ePtraceFailed = 1,
1257 eDupStdinFailed,
1258 eDupStdoutFailed,
1259 eDupStderrFailed,
1260 eChdirFailed,
1261 eExecFailed,
1262 eSetGidFailed
1263 };
1264
1265 // Child process.
1266 if (pid == 0)
1267 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001268 // FIXME consider opening a pipe between parent/child and have this forked child
1269 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001270
Todd Fiala75f47c32014-10-11 21:42:09 +00001271 // Start tracing this child that is about to exec.
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001272 NativeProcessLinux::PtraceWrapper(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001273 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001274 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001275
Pavel Labath493c3a12015-02-04 10:36:57 +00001276 // terminal has already dupped the tty descriptors to stdin/out/err.
1277 // This closes original fd from which they were copied (and avoids
1278 // leaking descriptors to the debugged process.
1279 terminal.CloseSlaveFileDescriptor();
1280
Todd Fialaaf245d12014-06-30 21:05:18 +00001281 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001282 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001283 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001284
1285 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001286 if (setpgid(0, 0) != 0)
1287 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001288 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001289 // Don't allow this to prevent an inferior exec.
1290 }
1291
1292 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001293 if (!args->m_stdin_path.empty ())
1294 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001295 exit(eDupStdinFailed);
1296
Todd Fiala75f47c32014-10-11 21:42:09 +00001297 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001298 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001299 exit(eDupStdoutFailed);
1300
Todd Fiala75f47c32014-10-11 21:42:09 +00001301 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001302 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001303 exit(eDupStderrFailed);
1304
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001305 // Close everything besides stdin, stdout, and stderr that has no file
1306 // action to avoid leaking
1307 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1308 if (!args->m_launch_info.GetFileActionForFD(fd))
1309 close(fd);
1310
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 // Change working directory
1312 if (working_dir != NULL && working_dir[0])
1313 if (0 != ::chdir(working_dir))
1314 exit(eChdirFailed);
1315
Todd Fiala0bce1b62014-08-17 00:10:50 +00001316 // Disable ASLR if requested.
1317 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1318 {
1319 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1320 if (old_personality == -1)
1321 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001322 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001323 }
1324 else
1325 {
1326 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1327 if (new_personality == -1)
1328 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001329 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001330 }
1331 else
1332 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001333 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001334 }
1335 }
1336 }
1337
Todd Fiala75f47c32014-10-11 21:42:09 +00001338 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001339 execve(argv[0],
1340 const_cast<char *const *>(argv),
1341 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001342
1343 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001344 exit(eExecFailed);
1345 }
1346
Todd Fiala75f47c32014-10-11 21:42:09 +00001347 //
1348 // This is the parent code here.
1349 //
1350 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1351
Todd Fialaaf245d12014-06-30 21:05:18 +00001352 // Wait for the child process to trap on its call to execve.
1353 ::pid_t wpid;
1354 int status;
1355 if ((wpid = waitpid(pid, &status, 0)) < 0)
1356 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001357 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001358 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001359 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1360 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001361
1362 // Mark the inferior as invalid.
1363 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001364 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001365
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001366 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001367 }
1368 else if (WIFEXITED(status))
1369 {
1370 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001371 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001372 switch (WEXITSTATUS(status))
1373 {
1374 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001375 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001376 break;
1377 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001378 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001379 break;
1380 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001381 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001382 break;
1383 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001384 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001385 break;
1386 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001387 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001388 break;
1389 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001390 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001391 break;
1392 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001393 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001394 break;
1395 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001396 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001397 break;
1398 }
1399
1400 if (log)
1401 {
1402 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1403 __FUNCTION__,
1404 WEXITSTATUS(status));
1405 }
1406
1407 // Mark the inferior as invalid.
1408 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001409 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001410
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001411 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001412 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001413 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001414 "Could not sync with inferior process.");
1415
1416 if (log)
1417 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1418
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001419 error = SetDefaultPtraceOpts(pid);
1420 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001421 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001422 if (log)
1423 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001424 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001425
1426 // Mark the inferior as invalid.
1427 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001428 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001429
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001430 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001431 }
1432
1433 // Release the master terminal descriptor and pass it off to the
1434 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001435 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1436 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001437
1438 // Set the terminal fd to be in non blocking mode (it simplifies the
1439 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1440 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001441 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1442 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001443 {
1444 if (log)
1445 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001446 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001447
1448 // Mark the inferior as invalid.
1449 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001450 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001451
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001452 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001453 }
1454
1455 if (log)
1456 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1457
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001458 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001459 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001460 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001461 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001462
1463 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001464 SetCurrentThreadID (thread_sp->GetID ());
1465 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001466
Todd Fialaaf245d12014-06-30 21:05:18 +00001467 if (log)
1468 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001469 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001470 {
1471 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1472 }
1473 else
1474 {
1475 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001476 __FUNCTION__, error.AsCString ());
1477 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001478 }
1479 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001480 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001481}
1482
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001483::pid_t
1484NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001485{
Todd Fialaaf245d12014-06-30 21:05:18 +00001486 lldb::ThreadSP inferior;
1487 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1488
1489 // Use a map to keep track of the threads which we have attached/need to attach.
1490 Host::TidMap tids_to_attach;
1491 if (pid <= 1)
1492 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001493 error.SetErrorToGenericError();
1494 error.SetErrorString("Attaching to process 1 is not allowed.");
1495 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001496 }
1497
1498 while (Host::FindProcessThreads(pid, tids_to_attach))
1499 {
1500 for (Host::TidMap::iterator it = tids_to_attach.begin();
1501 it != tids_to_attach.end();)
1502 {
1503 if (it->second == false)
1504 {
1505 lldb::tid_t tid = it->first;
1506
1507 // Attach to the requested process.
1508 // An attach will cause the thread to stop with a SIGSTOP.
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001509 NativeProcessLinux::PtraceWrapper(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001510 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001511 {
1512 // No such thread. The thread may have exited.
1513 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001514 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00001515 {
1516 it = tids_to_attach.erase(it);
1517 continue;
1518 }
1519 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001520 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001521 }
1522
1523 int status;
1524 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1525 // At this point we should have a thread stopped if waitpid succeeds.
1526 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1527 {
1528 // No such thread. The thread may have exited.
1529 // More error handling may be needed.
1530 if (errno == ESRCH)
1531 {
1532 it = tids_to_attach.erase(it);
1533 continue;
1534 }
1535 else
1536 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001537 error.SetErrorToErrno();
1538 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001539 }
1540 }
1541
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001542 error = SetDefaultPtraceOpts(tid);
1543 if (error.Fail())
1544 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001545
1546 if (log)
1547 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1548
1549 it->second = true;
1550
1551 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001552 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00001553 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001554
1555 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001556 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001557 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001558 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001559 }
1560
1561 // move the loop forward
1562 ++it;
1563 }
1564 }
1565
1566 if (tids_to_attach.size() > 0)
1567 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001568 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001569 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001570 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00001571 }
1572 else
1573 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001574 error.SetErrorToGenericError();
1575 error.SetErrorString("No such process.");
1576 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 }
1578
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001579 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001580}
1581
Chaoren Lin97ccc292015-02-03 01:51:12 +00001582Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001583NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1584{
1585 long ptrace_opts = 0;
1586
1587 // Have the child raise an event on exit. This is used to keep the child in
1588 // limbo until it is destroyed.
1589 ptrace_opts |= PTRACE_O_TRACEEXIT;
1590
1591 // Have the tracer trace threads which spawn in the inferior process.
1592 // TODO: if we want to support tracing the inferiors' child, add the
1593 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1594 ptrace_opts |= PTRACE_O_TRACECLONE;
1595
1596 // Have the tracer notify us before execve returns
1597 // (needed to disable legacy SIGTRAP generation)
1598 ptrace_opts |= PTRACE_O_TRACEEXEC;
1599
Chaoren Lin97ccc292015-02-03 01:51:12 +00001600 Error error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001601 NativeProcessLinux::PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001602 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001603}
1604
1605static ExitType convert_pid_status_to_exit_type (int status)
1606{
1607 if (WIFEXITED (status))
1608 return ExitType::eExitTypeExit;
1609 else if (WIFSIGNALED (status))
1610 return ExitType::eExitTypeSignal;
1611 else if (WIFSTOPPED (status))
1612 return ExitType::eExitTypeStop;
1613 else
1614 {
1615 // We don't know what this is.
1616 return ExitType::eExitTypeInvalid;
1617 }
1618}
1619
1620static int convert_pid_status_to_return_code (int status)
1621{
1622 if (WIFEXITED (status))
1623 return WEXITSTATUS (status);
1624 else if (WIFSIGNALED (status))
1625 return WTERMSIG (status);
1626 else if (WIFSTOPPED (status))
1627 return WSTOPSIG (status);
1628 else
1629 {
1630 // We don't know what this is.
1631 return ExitType::eExitTypeInvalid;
1632 }
1633}
1634
Pavel Labath1107b5a2015-04-17 14:07:49 +00001635// Handles all waitpid events from the inferior process.
1636void
1637NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00001638 bool exited,
1639 int signal,
1640 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00001641{
1642 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1643
Todd Fialaaf245d12014-06-30 21:05:18 +00001644 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001645 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001646
1647 // Handle when the thread exits.
1648 if (exited)
1649 {
1650 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001651 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 +00001652
1653 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001654 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001655
1656 if (is_main_thread)
1657 {
1658 // We only set the exit status and notify the delegate if we haven't already set the process
1659 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1660 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001661 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001662 if (!already_notified)
1663 {
1664 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001665 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 +00001666 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001667 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001668
1669 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001670 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001671 }
1672 else
1673 {
1674 if (log)
1675 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1676 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001677 }
1678 else
1679 {
1680 // Do we want to report to the delegate in this case? I think not. If this was an orderly
1681 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1682 // and we would have done an all-stop then.
1683 if (log)
1684 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 +00001685 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001686 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001687 }
1688
1689 // Get details on the signal raised.
1690 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001691 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00001692 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001693 {
1694 // We have retrieved the signal info. Dispatch appropriately.
1695 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001696 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001697 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001698 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001699 }
1700 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001701 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001702 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001703 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001704 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001705 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1706 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1707 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1708 // generally not needed (one use case is debugging background task being managed by a
1709 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1710 // stop which happens before the group stop. This done by MonitorSignal and works
1711 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001712 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001713 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);
1714 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001715 }
1716 else
1717 {
1718 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1719
1720 // A return value of ESRCH means the thread/process is no longer on the system,
1721 // so it was killed somehow outside of our control. Either way, we can't do anything
1722 // with it anymore.
1723
Todd Fialaaf245d12014-06-30 21:05:18 +00001724 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001725 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001726
1727 if (log)
1728 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001729 __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 +00001730
1731 if (is_main_thread)
1732 {
1733 // Notify the delegate - our process is not available but appears to have been killed outside
1734 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001735 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1736 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 }
1738 else
1739 {
1740 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1741 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001742 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 +00001743 }
1744 }
1745 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001746}
1747
1748void
Pavel Labath426bdf82015-04-28 07:51:52 +00001749NativeProcessLinux::WaitForNewThread(::pid_t tid)
1750{
1751 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1752
1753 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1754
1755 if (new_thread_sp)
1756 {
1757 // We are already tracking the thread - we got the event on the new thread (see
1758 // MonitorSignal) before this one. We are done.
1759 return;
1760 }
1761
1762 // The thread is not tracked yet, let's wait for it to appear.
1763 int status = -1;
1764 ::pid_t wait_pid;
1765 do
1766 {
1767 if (log)
1768 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1769 wait_pid = waitpid(tid, &status, __WALL);
1770 }
1771 while (wait_pid == -1 && errno == EINTR);
1772 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1773 // some checks just in case.
1774 if (wait_pid != tid) {
1775 if (log)
1776 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1777 // The only way I know of this could happen is if the whole process was
1778 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1779 return;
1780 }
1781 if (WIFEXITED(status))
1782 {
1783 if (log)
1784 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1785 // Also a very improbable event.
1786 return;
1787 }
1788
1789 siginfo_t info;
1790 Error error = GetSignalInfo(tid, &info);
1791 if (error.Fail())
1792 {
1793 if (log)
1794 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1795 return;
1796 }
1797
1798 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1799 {
1800 // We should be getting a thread creation signal here, but we received something
1801 // else. There isn't much we can do about it now, so we will just log that. Since the
1802 // thread is alive and we are receiving events from it, we shall pretend that it was
1803 // created properly.
1804 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);
1805 }
1806
1807 if (log)
1808 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1809 __FUNCTION__, GetID (), tid);
1810
1811 new_thread_sp = AddThread(tid);
1812 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1813 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001814 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001815}
1816
1817void
Todd Fialaaf245d12014-06-30 21:05:18 +00001818NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1819{
1820 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1821 const bool is_main_thread = (pid == GetID ());
1822
1823 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1824 if (!info)
1825 return;
1826
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001827 Mutex::Locker locker (m_threads_mutex);
1828
Todd Fialaaf245d12014-06-30 21:05:18 +00001829 // See if we can find a thread for this signal.
1830 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1831 if (!thread_sp)
1832 {
1833 if (log)
1834 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1835 }
1836
1837 switch (info->si_code)
1838 {
1839 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1840 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1841 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1842
1843 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1844 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001845 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001846 // creation.
1847 // We don't want to do anything with the parent thread so we just resume it. In case we
1848 // want to implement "break on thread creation" functionality, we would need to stop
1849 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001850
Pavel Labath426bdf82015-04-28 07:51:52 +00001851 unsigned long event_message = 0;
1852 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001853 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001854 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001855 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 +00001856 } else
1857 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001858
Pavel Labath5fd24c62015-04-23 09:04:35 +00001859 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001860 break;
1861 }
1862
1863 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001864 {
1865 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001866 if (log)
1867 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001868
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001869 // Exec clears any pending notifications.
1870 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001871
1872 // 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 +00001873 if (log)
1874 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1875
1876 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001877 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001878 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1879 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001880 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001881 main_thread_sp = thread_sp;
1882 if (log)
1883 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001884 }
1885 else
1886 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001887 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001888 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001889 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001890 }
1891 }
1892
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001893 m_threads.clear ();
1894
1895 if (main_thread_sp)
1896 {
1897 m_threads.push_back (main_thread_sp);
1898 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001899 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001900 }
1901 else
1902 {
1903 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1904 if (log)
1905 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1906 }
1907
Chaoren Linfa03ad22015-02-03 01:50:42 +00001908 // Tell coordinator about about the "new" (since exec) stopped main thread.
1909 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001910 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001911
1912 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1913 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001914 // Let our delegate know we have just exec'd.
1915 NotifyDidExec ();
1916
1917 // If we have a main thread, indicate we are stopped.
1918 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001919
1920 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001921 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001922
Todd Fialaaf245d12014-06-30 21:05:18 +00001923 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001924 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001925
1926 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1927 {
1928 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001929 // We don't want to do anything with the thread so we just resume it. In case we
1930 // want to implement "break on thread exit" functionality, we would need to stop
1931 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001932
Todd Fialaaf245d12014-06-30 21:05:18 +00001933 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001934 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001935 data = -1;
1936
1937 if (log)
1938 {
1939 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1940 __FUNCTION__,
1941 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1942 pid,
1943 is_main_thread ? "is main thread" : "not main thread");
1944 }
1945
Todd Fialaaf245d12014-06-30 21:05:18 +00001946 if (is_main_thread)
1947 {
1948 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001949 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001950
Pavel Labath6e351632015-05-15 13:30:59 +00001951 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001952
1953 break;
1954 }
1955
1956 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001957 case TRAP_TRACE: // We receive this on single stepping.
1958 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001959 if (thread_sp)
1960 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001961 // If a watchpoint was hit, report it
1962 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001963 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001964 if (error.Fail() && log)
1965 log->Printf("NativeProcessLinux::%s() "
1966 "received error while checking for watchpoint hits, "
1967 "pid = %" PRIu64 " error = %s",
1968 __FUNCTION__, pid, error.AsCString());
1969 if (wp_index != LLDB_INVALID_INDEX32)
1970 {
1971 MonitorWatchpoint(pid, thread_sp, wp_index);
1972 break;
1973 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001974 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001975 // Otherwise, report step over
1976 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001977 break;
1978
1979 case SI_KERNEL:
1980 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001981 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001982 break;
1983
1984 case SIGTRAP:
1985 case (SIGTRAP | 0x80):
1986 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001987 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1988
Todd Fialaaf245d12014-06-30 21:05:18 +00001989 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001990 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001991 break;
1992
1993 default:
1994 assert(false && "Unexpected SIGTRAP code!");
1995 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001996 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1997 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001998 break;
1999
2000 }
2001}
2002
2003void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002004NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2005{
2006 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2007 if (log)
2008 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2009 __FUNCTION__, pid);
2010
2011 if (thread_sp)
2012 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2013
2014 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002015 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002016
2017 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2018 // This would have already happened at the time the Resume() with step operation was signaled.
2019 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2020 // once all running threads have checked in as stopped.
2021 SetCurrentThreadID(pid);
2022 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00002023 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002024}
2025
2026void
2027NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2028{
2029 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2030 if (log)
2031 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2032 __FUNCTION__, pid);
2033
2034 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002035 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002036
2037 // Mark the thread as stopped at breakpoint.
2038 if (thread_sp)
2039 {
2040 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2041 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2042 if (error.Fail())
2043 if (log)
2044 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2045 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002046
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002047 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002048 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002049 }
2050 else
2051 if (log)
2052 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2053 "warning, cannot process software breakpoint since no thread metadata",
2054 __FUNCTION__, pid);
2055
2056
2057 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002058 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002059}
2060
2061void
2062NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2063{
2064 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2065 if (log)
2066 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2067 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2068 __FUNCTION__, pid, wp_index);
2069
2070 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002071 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002072
2073 // Mark the thread as stopped at watchpoint.
2074 // The address is at (lldb::addr_t)info->si_addr if we need it.
2075 lldbassert(thread_sp && "thread_sp cannot be NULL");
2076 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2077
2078 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002079 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002080}
2081
2082void
Todd Fialaaf245d12014-06-30 21:05:18 +00002083NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2084{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002085 assert (info && "null info");
2086 if (!info)
2087 return;
2088
2089 const int signo = info->si_signo;
2090 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002091
2092 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2093
2094 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2095 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2096 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2097 //
2098 // IOW, user generated signals never generate what we consider to be a
2099 // "crash".
2100 //
2101 // Similarly, ACK signals generated by this monitor.
2102
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002103 Mutex::Locker locker (m_threads_mutex);
2104
Todd Fialaaf245d12014-06-30 21:05:18 +00002105 // See if we can find a thread for this signal.
2106 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2107 if (!thread_sp)
2108 {
2109 if (log)
2110 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2111 }
2112
2113 // Handle the signal.
2114 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2115 {
2116 if (log)
2117 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2118 __FUNCTION__,
2119 GetUnixSignals ().GetSignalAsCString (signo),
2120 signo,
2121 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2122 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002123 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002124 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002125 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002126
Todd Fiala58a2f662014-08-12 17:02:07 +00002127 // Check for new thread notification.
2128 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2129 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002130 // A new thread creation is being signaled. This is one of two parts that come in
2131 // a non-deterministic order. This code handles the case where the new thread event comes
2132 // before the event on the parent thread. For the opposite case see code in
2133 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002134 if (log)
2135 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2136 __FUNCTION__, GetID (), pid);
2137
Pavel Labath5fd24c62015-04-23 09:04:35 +00002138 thread_sp = AddThread(pid);
2139 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2140 // We can now resume the newly created thread.
2141 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2142 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002143 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002144 // Done handling.
2145 return;
2146 }
2147
2148 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002149 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002150 {
2151 // This is a tgkill()-based stop.
2152 if (thread_sp)
2153 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002154 if (log)
2155 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2156 __FUNCTION__,
2157 GetID (),
2158 pid);
2159
Chaoren Linaab58632015-02-03 01:50:57 +00002160 // Check that we're not already marked with a stop reason.
2161 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2162 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2163 // and that, without an intervening resume, we received another stop. It is more likely
2164 // that we are missing the marking of a run state somewhere if we find that the thread was
2165 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002166 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2167 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002168
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002169 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002170 if (!StateIsStoppedState (thread_state, false))
2171 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00002172 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2173 // Generally, these are not important stops and we don't want to report them as
2174 // they are just used to stop other threads when one thread (the one with the
2175 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2176 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2177 // leave the signal intact if this is the thread that was chosen as the
2178 // triggering thread.
2179 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002180 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00002181 else
2182 linux_thread_sp->SetStoppedBySignal(0);
2183
Chaoren Linaab58632015-02-03 01:50:57 +00002184 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002185 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00002186 }
2187 else
2188 {
2189 if (log)
2190 {
2191 // Retrieve the signal name if the thread was stopped by a signal.
2192 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002193 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002194 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2195 if (!signal_name)
2196 signal_name = "<no-signal-name>";
2197
2198 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",
2199 __FUNCTION__,
2200 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002201 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002202 StateAsCString (thread_state),
2203 stop_signo,
2204 signal_name);
2205 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002206 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00002207 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002208 }
2209
2210 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002211 return;
2212 }
2213
2214 if (log)
2215 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2216
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002217 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002218 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002219
Pavel Labathc4e25c92015-05-29 10:13:03 +00002220 if (thread_sp)
2221 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002222
2223 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00002224 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002225}
2226
Tamas Berghammere7708682015-04-22 10:00:23 +00002227namespace {
2228
2229struct EmulatorBaton
2230{
2231 NativeProcessLinux* m_process;
2232 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002233
Pavel Labath6648fcc2015-04-27 09:21:14 +00002234 // eRegisterKindDWARF -> RegsiterValue
2235 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2236
2237 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002238 m_process(process), m_reg_context(reg_context) {}
2239};
2240
2241} // anonymous namespace
2242
2243static size_t
2244ReadMemoryCallback (EmulateInstruction *instruction,
2245 void *baton,
2246 const EmulateInstruction::Context &context,
2247 lldb::addr_t addr,
2248 void *dst,
2249 size_t length)
2250{
2251 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2252
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002253 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002254 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2255 return bytes_read;
2256}
2257
2258static bool
2259ReadRegisterCallback (EmulateInstruction *instruction,
2260 void *baton,
2261 const RegisterInfo *reg_info,
2262 RegisterValue &reg_value)
2263{
2264 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2265
Pavel Labath6648fcc2015-04-27 09:21:14 +00002266 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2267 if (it != emulator_baton->m_register_values.end())
2268 {
2269 reg_value = it->second;
2270 return true;
2271 }
2272
Tamas Berghammere7708682015-04-22 10:00:23 +00002273 // The emulator only fill in the dwarf regsiter numbers (and in some case
2274 // the generic register numbers). Get the full register info from the
2275 // register context based on the dwarf register numbers.
2276 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2277 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2278
2279 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002280 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00002281 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002282
Pavel Labath6648fcc2015-04-27 09:21:14 +00002283 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002284}
2285
2286static bool
2287WriteRegisterCallback (EmulateInstruction *instruction,
2288 void *baton,
2289 const EmulateInstruction::Context &context,
2290 const RegisterInfo *reg_info,
2291 const RegisterValue &reg_value)
2292{
2293 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002294 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002295 return true;
2296}
2297
2298static size_t
2299WriteMemoryCallback (EmulateInstruction *instruction,
2300 void *baton,
2301 const EmulateInstruction::Context &context,
2302 lldb::addr_t addr,
2303 const void *dst,
2304 size_t length)
2305{
2306 return length;
2307}
2308
2309static lldb::addr_t
2310ReadFlags (NativeRegisterContext* regsiter_context)
2311{
2312 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2313 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2314 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2315}
2316
2317Error
2318NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2319{
2320 Error error;
2321 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2322
2323 std::unique_ptr<EmulateInstruction> emulator_ap(
2324 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2325
2326 if (emulator_ap == nullptr)
2327 return Error("Instruction emulator not found!");
2328
2329 EmulatorBaton baton(this, register_context_sp.get());
2330 emulator_ap->SetBaton(&baton);
2331 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2332 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2333 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2334 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2335
2336 if (!emulator_ap->ReadInstruction())
2337 return Error("Read instruction failed!");
2338
Pavel Labath6648fcc2015-04-27 09:21:14 +00002339 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2340
2341 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2342 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2343
2344 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2345 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2346
Tamas Berghammere7708682015-04-22 10:00:23 +00002347 lldb::addr_t next_pc;
2348 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002349 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002350 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002351 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2352 next_pc = pc_it->second.GetAsUInt64();
2353
2354 if (flags_it != baton.m_register_values.end())
2355 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002356 else
2357 next_flags = ReadFlags (register_context_sp.get());
2358 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002359 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002360 {
2361 // Emulate instruction failed and it haven't changed PC. Advance PC
2362 // with the size of the current opcode because the emulation of all
2363 // PC modifying instruction should be successful. The failure most
2364 // likely caused by a not supported instruction which don't modify PC.
2365 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2366 next_flags = ReadFlags (register_context_sp.get());
2367 }
2368 else
2369 {
2370 // The instruction emulation failed after it modified the PC. It is an
2371 // unknown error where we can't continue because the next instruction is
2372 // modifying the PC but we don't know how.
2373 return Error ("Instruction emulation failed unexpectedly.");
2374 }
2375
2376 if (m_arch.GetMachine() == llvm::Triple::arm)
2377 {
2378 if (next_flags & 0x20)
2379 {
2380 // Thumb mode
2381 error = SetSoftwareBreakpoint(next_pc, 2);
2382 }
2383 else
2384 {
2385 // Arm mode
2386 error = SetSoftwareBreakpoint(next_pc, 4);
2387 }
2388 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002389 else if (m_arch.GetMachine() == llvm::Triple::mips64
2390 || m_arch.GetMachine() == llvm::Triple::mips64el)
2391 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00002392 else
2393 {
2394 // No size hint is given for the next breakpoint
2395 error = SetSoftwareBreakpoint(next_pc, 0);
2396 }
2397
Tamas Berghammere7708682015-04-22 10:00:23 +00002398 if (error.Fail())
2399 return error;
2400
2401 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2402
2403 return Error();
2404}
2405
2406bool
2407NativeProcessLinux::SupportHardwareSingleStepping() const
2408{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00002409 if (m_arch.GetMachine() == llvm::Triple::arm
2410 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2411 return false;
2412 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00002413}
2414
Todd Fialaaf245d12014-06-30 21:05:18 +00002415Error
2416NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2417{
Todd Fialaaf245d12014-06-30 21:05:18 +00002418 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2419 if (log)
2420 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2421
Tamas Berghammere7708682015-04-22 10:00:23 +00002422 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00002423
Pavel Labath45f5cb32015-05-05 15:05:50 +00002424 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002425 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00002426
Tamas Berghammere7708682015-04-22 10:00:23 +00002427 if (software_single_step)
2428 {
2429 for (auto thread_sp : m_threads)
2430 {
2431 assert (thread_sp && "thread list should not contain NULL threads");
2432
2433 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2434 if (action == nullptr)
2435 continue;
2436
2437 if (action->state == eStateStepping)
2438 {
2439 Error error = SetupSoftwareSingleStepping(thread_sp);
2440 if (error.Fail())
2441 return error;
2442 }
2443 }
2444 }
2445
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002446 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00002447 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002448 assert (thread_sp && "thread list should not contain NULL threads");
2449
2450 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2451
2452 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002453 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002454 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002455 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2456 __FUNCTION__, GetID (), thread_sp->GetID ());
2457 continue;
2458 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002459
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002460 if (log)
2461 {
2462 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2463 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2464 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002465
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002466 switch (action->state)
2467 {
2468 case eStateRunning:
2469 {
2470 // Run the thread, possibly feeding it the signal.
2471 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002472 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002473 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2474 {
2475 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2476 // Pass this signal number on to the inferior to handle.
2477 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2478 if (resume_result.Success())
2479 SetState(eStateRunning, true);
2480 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002481 },
2482 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002483 break;
2484 }
2485
2486 case eStateStepping:
2487 {
2488 // Request the step.
2489 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002490 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00002491 [=](lldb::tid_t tid_to_step, bool supress_signal)
2492 {
2493 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00002494
Pavel Labathc0765592015-05-06 10:46:34 +00002495 Error step_result;
2496 if (software_single_step)
2497 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2498 else
2499 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00002500
Pavel Labathc0765592015-05-06 10:46:34 +00002501 assert (step_result.Success() && "SingleStep() failed");
2502 if (step_result.Success())
2503 SetState(eStateStepping, true);
2504 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002505 },
2506 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002507 break;
2508 }
2509
2510 case eStateSuspended:
2511 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00002512 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002513
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002514 default:
2515 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2516 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002517 }
2518 }
2519
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002520 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002521}
2522
2523Error
2524NativeProcessLinux::Halt ()
2525{
2526 Error error;
2527
Todd Fialaaf245d12014-06-30 21:05:18 +00002528 if (kill (GetID (), SIGSTOP) != 0)
2529 error.SetErrorToErrno ();
2530
2531 return error;
2532}
2533
2534Error
2535NativeProcessLinux::Detach ()
2536{
2537 Error error;
2538
2539 // Tell ptrace to detach from the process.
2540 if (GetID () != LLDB_INVALID_PROCESS_ID)
2541 error = Detach (GetID ());
2542
2543 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00002544 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00002545
2546 // No error.
2547 return error;
2548}
2549
2550Error
2551NativeProcessLinux::Signal (int signo)
2552{
2553 Error error;
2554
2555 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2556 if (log)
2557 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2558 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2559
2560 if (kill(GetID(), signo))
2561 error.SetErrorToErrno();
2562
2563 return error;
2564}
2565
2566Error
Chaoren Line9547b82015-02-03 01:51:00 +00002567NativeProcessLinux::Interrupt ()
2568{
2569 // Pick a running thread (or if none, a not-dead stopped thread) as
2570 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00002571 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2572
2573 NativeThreadProtocolSP running_thread_sp;
2574 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002575
2576 if (log)
2577 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2578
Pavel Labath45f5cb32015-05-05 15:05:50 +00002579 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002580 Mutex::Locker locker (m_threads_mutex);
2581
2582 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00002583 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002584 // The thread shouldn't be null but lets just cover that here.
2585 if (!thread_sp)
2586 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00002587
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002588 // If we have a running or stepping thread, we'll call that the
2589 // target of the interrupt.
2590 const auto thread_state = thread_sp->GetState ();
2591 if (thread_state == eStateRunning ||
2592 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00002593 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002594 running_thread_sp = thread_sp;
2595 break;
2596 }
2597 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2598 {
2599 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
2600 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00002601 }
2602 }
2603
2604 if (!running_thread_sp && !stopped_thread_sp)
2605 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002606 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00002607 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00002608 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002609
Chaoren Line9547b82015-02-03 01:51:00 +00002610 return error;
2611 }
2612
2613 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2614
2615 if (log)
2616 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2617 __FUNCTION__,
2618 GetID (),
2619 running_thread_sp ? "running" : "stopped",
2620 deferred_signal_thread_sp->GetID ());
2621
Pavel Labathed89c7f2015-05-06 12:22:37 +00002622 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00002623
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002624 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00002625}
2626
2627Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002628NativeProcessLinux::Kill ()
2629{
2630 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2631 if (log)
2632 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2633
2634 Error error;
2635
2636 switch (m_state)
2637 {
2638 case StateType::eStateInvalid:
2639 case StateType::eStateExited:
2640 case StateType::eStateCrashed:
2641 case StateType::eStateDetached:
2642 case StateType::eStateUnloaded:
2643 // Nothing to do - the process is already dead.
2644 if (log)
2645 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2646 return error;
2647
2648 case StateType::eStateConnected:
2649 case StateType::eStateAttaching:
2650 case StateType::eStateLaunching:
2651 case StateType::eStateStopped:
2652 case StateType::eStateRunning:
2653 case StateType::eStateStepping:
2654 case StateType::eStateSuspended:
2655 // We can try to kill a process in these states.
2656 break;
2657 }
2658
2659 if (kill (GetID (), SIGKILL) != 0)
2660 {
2661 error.SetErrorToErrno ();
2662 return error;
2663 }
2664
2665 return error;
2666}
2667
2668static Error
2669ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2670{
2671 memory_region_info.Clear();
2672
2673 StringExtractor line_extractor (maps_line.c_str ());
2674
2675 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
2676 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
2677
2678 // Parse out the starting address
2679 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2680
2681 // Parse out hyphen separating start and end address from range.
2682 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2683 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2684
2685 // Parse out the ending address
2686 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2687
2688 // Parse out the space after the address.
2689 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2690 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2691
2692 // Save the range.
2693 memory_region_info.GetRange ().SetRangeBase (start_address);
2694 memory_region_info.GetRange ().SetRangeEnd (end_address);
2695
2696 // Parse out each permission entry.
2697 if (line_extractor.GetBytesLeft () < 4)
2698 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2699
2700 // Handle read permission.
2701 const char read_perm_char = line_extractor.GetChar ();
2702 if (read_perm_char == 'r')
2703 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2704 else
2705 {
2706 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2707 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2708 }
2709
2710 // Handle write permission.
2711 const char write_perm_char = line_extractor.GetChar ();
2712 if (write_perm_char == 'w')
2713 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2714 else
2715 {
2716 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2717 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2718 }
2719
2720 // Handle execute permission.
2721 const char exec_perm_char = line_extractor.GetChar ();
2722 if (exec_perm_char == 'x')
2723 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2724 else
2725 {
2726 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2727 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2728 }
2729
2730 return Error ();
2731}
2732
2733Error
2734NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2735{
2736 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2737 // with no perms if it is not mapped.
2738
2739 // Use an approach that reads memory regions from /proc/{pid}/maps.
2740 // Assume proc maps entries are in ascending order.
2741 // FIXME assert if we find differently.
2742 Mutex::Locker locker (m_mem_region_cache_mutex);
2743
2744 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2745 Error error;
2746
2747 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2748 {
2749 // We're done.
2750 error.SetErrorString ("unsupported");
2751 return error;
2752 }
2753
2754 // If our cache is empty, pull the latest. There should always be at least one memory region
2755 // if memory region handling is supported.
2756 if (m_mem_region_cache.empty ())
2757 {
2758 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2759 [&] (const std::string &line) -> bool
2760 {
2761 MemoryRegionInfo info;
2762 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2763 if (parse_error.Success ())
2764 {
2765 m_mem_region_cache.push_back (info);
2766 return true;
2767 }
2768 else
2769 {
2770 if (log)
2771 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2772 return false;
2773 }
2774 });
2775
2776 // If we had an error, we'll mark unsupported.
2777 if (error.Fail ())
2778 {
2779 m_supports_mem_region = LazyBool::eLazyBoolNo;
2780 return error;
2781 }
2782 else if (m_mem_region_cache.empty ())
2783 {
2784 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2785 // is supported. Assume we don't support map entries via procfs.
2786 if (log)
2787 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2788 m_supports_mem_region = LazyBool::eLazyBoolNo;
2789 error.SetErrorString ("not supported");
2790 return error;
2791 }
2792
2793 if (log)
2794 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2795
2796 // We support memory retrieval, remember that.
2797 m_supports_mem_region = LazyBool::eLazyBoolYes;
2798 }
2799 else
2800 {
2801 if (log)
2802 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2803 }
2804
2805 lldb::addr_t prev_base_address = 0;
2806
2807 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2808 // There can be a ton of regions on pthreads apps with lots of threads.
2809 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2810 {
2811 MemoryRegionInfo &proc_entry_info = *it;
2812
2813 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2814 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2815 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2816
2817 // If the target address comes before this entry, indicate distance to next region.
2818 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2819 {
2820 range_info.GetRange ().SetRangeBase (load_addr);
2821 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2822 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2823 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2824 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2825
2826 return error;
2827 }
2828 else if (proc_entry_info.GetRange ().Contains (load_addr))
2829 {
2830 // The target address is within the memory region we're processing here.
2831 range_info = proc_entry_info;
2832 return error;
2833 }
2834
2835 // The target memory address comes somewhere after the region we just parsed.
2836 }
2837
2838 // If we made it here, we didn't find an entry that contained the given address.
2839 error.SetErrorString ("address comes after final region");
2840
2841 if (log)
2842 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
2843
2844 return error;
2845}
2846
2847void
2848NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2849{
2850 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2851 if (log)
2852 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2853
2854 {
2855 Mutex::Locker locker (m_mem_region_cache_mutex);
2856 if (log)
2857 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2858 m_mem_region_cache.clear ();
2859 }
2860}
2861
2862Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002863NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002864{
2865 // FIXME implementing this requires the equivalent of
2866 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2867 // functional ThreadPlans working with Native*Protocol.
2868#if 1
2869 return Error ("not implemented yet");
2870#else
2871 addr = LLDB_INVALID_ADDRESS;
2872
2873 unsigned prot = 0;
2874 if (permissions & lldb::ePermissionsReadable)
2875 prot |= eMmapProtRead;
2876 if (permissions & lldb::ePermissionsWritable)
2877 prot |= eMmapProtWrite;
2878 if (permissions & lldb::ePermissionsExecutable)
2879 prot |= eMmapProtExec;
2880
2881 // TODO implement this directly in NativeProcessLinux
2882 // (and lift to NativeProcessPOSIX if/when that class is
2883 // refactored out).
2884 if (InferiorCallMmap(this, addr, 0, size, prot,
2885 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2886 m_addr_to_mmap_size[addr] = size;
2887 return Error ();
2888 } else {
2889 addr = LLDB_INVALID_ADDRESS;
2890 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2891 }
2892#endif
2893}
2894
2895Error
2896NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2897{
2898 // FIXME see comments in AllocateMemory - required lower-level
2899 // bits not in place yet (ThreadPlans)
2900 return Error ("not implemented");
2901}
2902
2903lldb::addr_t
2904NativeProcessLinux::GetSharedLibraryInfoAddress ()
2905{
2906#if 1
2907 // punt on this for now
2908 return LLDB_INVALID_ADDRESS;
2909#else
2910 // Return the image info address for the exe module
2911#if 1
2912 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2913
2914 ModuleSP module_sp;
2915 Error error = GetExeModuleSP (module_sp);
2916 if (error.Fail ())
2917 {
2918 if (log)
2919 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2920 return LLDB_INVALID_ADDRESS;
2921 }
2922
2923 if (module_sp == nullptr)
2924 {
2925 if (log)
2926 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2927 return LLDB_INVALID_ADDRESS;
2928 }
2929
2930 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2931 if (object_file_sp == nullptr)
2932 {
2933 if (log)
2934 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2935 return LLDB_INVALID_ADDRESS;
2936 }
2937
2938 return obj_file_sp->GetImageInfoAddress();
2939#else
2940 Target *target = &GetTarget();
2941 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2942 Address addr = obj_file->GetImageInfoAddress(target);
2943
2944 if (addr.IsValid())
2945 return addr.GetLoadAddress(target);
2946 return LLDB_INVALID_ADDRESS;
2947#endif
2948#endif // punt on this for now
2949}
2950
2951size_t
2952NativeProcessLinux::UpdateThreads ()
2953{
2954 // The NativeProcessLinux monitoring threads are always up to date
2955 // with respect to thread state and they keep the thread list
2956 // populated properly. All this method needs to do is return the
2957 // thread count.
2958 Mutex::Locker locker (m_threads_mutex);
2959 return m_threads.size ();
2960}
2961
2962bool
2963NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2964{
2965 arch = m_arch;
2966 return true;
2967}
2968
2969Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002970NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002971{
2972 // FIXME put this behind a breakpoint protocol class that can be
2973 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002974 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002975 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002976 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00002977
2978 switch (m_arch.GetMachine ())
2979 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002980 case llvm::Triple::aarch64:
2981 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
2982 return Error ();
2983
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002984 case llvm::Triple::arm:
2985 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
2986 return Error ();
2987
Todd Fialaaf245d12014-06-30 21:05:18 +00002988 case llvm::Triple::x86:
2989 case llvm::Triple::x86_64:
2990 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2991 return Error ();
2992
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002993 case llvm::Triple::mips64:
2994 case llvm::Triple::mips64el:
2995 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
2996 return Error ();
2997
Todd Fialaaf245d12014-06-30 21:05:18 +00002998 default:
2999 assert(false && "CPU type not supported!");
3000 return Error ("CPU type not supported");
3001 }
3002}
3003
3004Error
3005NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3006{
3007 if (hardware)
3008 return Error ("NativeProcessLinux does not support hardware breakpoints");
3009 else
3010 return SetSoftwareBreakpoint (addr, size);
3011}
3012
3013Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003014NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3015 size_t &actual_opcode_size,
3016 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003017{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003018 // FIXME put this behind a breakpoint protocol class that can be set per
3019 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003020 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003021 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3022 // linux kernel does otherwise.
3023 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003024 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003025 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003026 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003027 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003028
3029 switch (m_arch.GetMachine ())
3030 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003031 case llvm::Triple::aarch64:
3032 trap_opcode_bytes = g_aarch64_opcode;
3033 actual_opcode_size = sizeof(g_aarch64_opcode);
3034 return Error ();
3035
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003036 case llvm::Triple::arm:
3037 switch (trap_opcode_size_hint)
3038 {
3039 case 2:
3040 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3041 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3042 return Error ();
3043 case 4:
3044 trap_opcode_bytes = g_arm_breakpoint_opcode;
3045 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3046 return Error ();
3047 default:
3048 assert(false && "Unrecognised trap opcode size hint!");
3049 return Error ("Unrecognised trap opcode size hint!");
3050 }
3051
Todd Fialaaf245d12014-06-30 21:05:18 +00003052 case llvm::Triple::x86:
3053 case llvm::Triple::x86_64:
3054 trap_opcode_bytes = g_i386_opcode;
3055 actual_opcode_size = sizeof(g_i386_opcode);
3056 return Error ();
3057
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003058 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003059 trap_opcode_bytes = g_mips64_opcode;
3060 actual_opcode_size = sizeof(g_mips64_opcode);
3061 return Error ();
3062
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003063 case llvm::Triple::mips64el:
3064 trap_opcode_bytes = g_mips64el_opcode;
3065 actual_opcode_size = sizeof(g_mips64el_opcode);
3066 return Error ();
3067
Todd Fialaaf245d12014-06-30 21:05:18 +00003068 default:
3069 assert(false && "CPU type not supported!");
3070 return Error ("CPU type not supported");
3071 }
3072}
3073
3074#if 0
3075ProcessMessage::CrashReason
3076NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3077{
3078 ProcessMessage::CrashReason reason;
3079 assert(info->si_signo == SIGSEGV);
3080
3081 reason = ProcessMessage::eInvalidCrashReason;
3082
3083 switch (info->si_code)
3084 {
3085 default:
3086 assert(false && "unexpected si_code for SIGSEGV");
3087 break;
3088 case SI_KERNEL:
3089 // Linux will occasionally send spurious SI_KERNEL codes.
3090 // (this is poorly documented in sigaction)
3091 // One way to get this is via unaligned SIMD loads.
3092 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3093 break;
3094 case SEGV_MAPERR:
3095 reason = ProcessMessage::eInvalidAddress;
3096 break;
3097 case SEGV_ACCERR:
3098 reason = ProcessMessage::ePrivilegedAddress;
3099 break;
3100 }
3101
3102 return reason;
3103}
3104#endif
3105
3106
3107#if 0
3108ProcessMessage::CrashReason
3109NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3110{
3111 ProcessMessage::CrashReason reason;
3112 assert(info->si_signo == SIGILL);
3113
3114 reason = ProcessMessage::eInvalidCrashReason;
3115
3116 switch (info->si_code)
3117 {
3118 default:
3119 assert(false && "unexpected si_code for SIGILL");
3120 break;
3121 case ILL_ILLOPC:
3122 reason = ProcessMessage::eIllegalOpcode;
3123 break;
3124 case ILL_ILLOPN:
3125 reason = ProcessMessage::eIllegalOperand;
3126 break;
3127 case ILL_ILLADR:
3128 reason = ProcessMessage::eIllegalAddressingMode;
3129 break;
3130 case ILL_ILLTRP:
3131 reason = ProcessMessage::eIllegalTrap;
3132 break;
3133 case ILL_PRVOPC:
3134 reason = ProcessMessage::ePrivilegedOpcode;
3135 break;
3136 case ILL_PRVREG:
3137 reason = ProcessMessage::ePrivilegedRegister;
3138 break;
3139 case ILL_COPROC:
3140 reason = ProcessMessage::eCoprocessorError;
3141 break;
3142 case ILL_BADSTK:
3143 reason = ProcessMessage::eInternalStackError;
3144 break;
3145 }
3146
3147 return reason;
3148}
3149#endif
3150
3151#if 0
3152ProcessMessage::CrashReason
3153NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3154{
3155 ProcessMessage::CrashReason reason;
3156 assert(info->si_signo == SIGFPE);
3157
3158 reason = ProcessMessage::eInvalidCrashReason;
3159
3160 switch (info->si_code)
3161 {
3162 default:
3163 assert(false && "unexpected si_code for SIGFPE");
3164 break;
3165 case FPE_INTDIV:
3166 reason = ProcessMessage::eIntegerDivideByZero;
3167 break;
3168 case FPE_INTOVF:
3169 reason = ProcessMessage::eIntegerOverflow;
3170 break;
3171 case FPE_FLTDIV:
3172 reason = ProcessMessage::eFloatDivideByZero;
3173 break;
3174 case FPE_FLTOVF:
3175 reason = ProcessMessage::eFloatOverflow;
3176 break;
3177 case FPE_FLTUND:
3178 reason = ProcessMessage::eFloatUnderflow;
3179 break;
3180 case FPE_FLTRES:
3181 reason = ProcessMessage::eFloatInexactResult;
3182 break;
3183 case FPE_FLTINV:
3184 reason = ProcessMessage::eFloatInvalidOperation;
3185 break;
3186 case FPE_FLTSUB:
3187 reason = ProcessMessage::eFloatSubscriptRange;
3188 break;
3189 }
3190
3191 return reason;
3192}
3193#endif
3194
3195#if 0
3196ProcessMessage::CrashReason
3197NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3198{
3199 ProcessMessage::CrashReason reason;
3200 assert(info->si_signo == SIGBUS);
3201
3202 reason = ProcessMessage::eInvalidCrashReason;
3203
3204 switch (info->si_code)
3205 {
3206 default:
3207 assert(false && "unexpected si_code for SIGBUS");
3208 break;
3209 case BUS_ADRALN:
3210 reason = ProcessMessage::eIllegalAlignment;
3211 break;
3212 case BUS_ADRERR:
3213 reason = ProcessMessage::eIllegalAddress;
3214 break;
3215 case BUS_OBJERR:
3216 reason = ProcessMessage::eHardwareError;
3217 break;
3218 }
3219
3220 return reason;
3221}
3222#endif
3223
Todd Fialaaf245d12014-06-30 21:05:18 +00003224Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003225NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3226{
3227 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3228 // for it.
3229 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3230 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3231}
3232
3233Error
3234NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3235{
3236 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3237 // for it.
3238 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3239 return NativeProcessProtocol::RemoveWatchpoint(addr);
3240}
3241
3242Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003243NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003244{
3245 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003246 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003247 return op.GetError ();
3248}
3249
3250Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003251NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3252{
3253 Error error = ReadMemory(addr, buf, size, bytes_read);
3254 if (error.Fail()) return error;
3255 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3256}
3257
3258Error
3259NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003260{
3261 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003262 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003263 return op.GetError ();
3264}
3265
Chaoren Lin97ccc292015-02-03 01:51:12 +00003266Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003267NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3268{
Todd Fialaaf245d12014-06-30 21:05:18 +00003269 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3270
3271 if (log)
3272 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
3273 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00003274 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003275 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003276 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00003277 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3278 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003279}
3280
Chaoren Lin97ccc292015-02-03 01:51:12 +00003281Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003282NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3283{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003284 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003285 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003286 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003287}
3288
Chaoren Lin97ccc292015-02-03 01:51:12 +00003289Error
3290NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00003291{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003292 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003293 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003294 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003295}
3296
Chaoren Lin97ccc292015-02-03 01:51:12 +00003297Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003298NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3299{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003300 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003301 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003302 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003303}
3304
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003305Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003306NativeProcessLinux::Detach(lldb::tid_t tid)
3307{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003308 if (tid == LLDB_INVALID_THREAD_ID)
3309 return Error();
3310
3311 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003312 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003313 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003314}
3315
3316bool
3317NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3318{
3319 int target_fd = open(path, flags, 0666);
3320
3321 if (target_fd == -1)
3322 return false;
3323
Pavel Labath493c3a12015-02-04 10:36:57 +00003324 if (dup2(target_fd, fd) == -1)
3325 return false;
3326
3327 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00003328}
3329
3330void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003331NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00003332{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003333 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00003334 error = m_monitor_up->Initialize();
3335 if (error.Fail()) {
3336 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00003337 }
3338}
3339
Todd Fialaaf245d12014-06-30 21:05:18 +00003340bool
3341NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3342{
3343 for (auto thread_sp : m_threads)
3344 {
3345 assert (thread_sp && "thread list should not contain NULL threads");
3346 if (thread_sp->GetID () == thread_id)
3347 {
3348 // We have this thread.
3349 return true;
3350 }
3351 }
3352
3353 // We don't have this thread.
3354 return false;
3355}
3356
3357NativeThreadProtocolSP
3358NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3359{
3360 // CONSIDER organize threads by map - we can do better than linear.
3361 for (auto thread_sp : m_threads)
3362 {
3363 if (thread_sp->GetID () == thread_id)
3364 return thread_sp;
3365 }
3366
3367 // We don't have this thread.
3368 return NativeThreadProtocolSP ();
3369}
3370
3371bool
3372NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3373{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003374 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3375
3376 if (log)
3377 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
3378
3379 bool found = false;
3380
Todd Fialaaf245d12014-06-30 21:05:18 +00003381 Mutex::Locker locker (m_threads_mutex);
3382 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3383 {
3384 if (*it && ((*it)->GetID () == thread_id))
3385 {
3386 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003387 found = true;
3388 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00003389 }
3390 }
3391
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003392 // If we have a pending notification, remove this from the set.
3393 if (m_pending_notification_up)
3394 {
3395 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003396 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003397 }
3398
3399 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00003400}
3401
3402NativeThreadProtocolSP
3403NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3404{
3405 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3406
3407 Mutex::Locker locker (m_threads_mutex);
3408
3409 if (log)
3410 {
3411 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3412 __FUNCTION__,
3413 GetID (),
3414 thread_id);
3415 }
3416
3417 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3418
3419 // If this is the first thread, save it as the current thread
3420 if (m_threads.empty ())
3421 SetCurrentThreadID (thread_id);
3422
3423 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3424 m_threads.push_back (thread_sp);
3425
3426 return thread_sp;
3427}
3428
Todd Fialaaf245d12014-06-30 21:05:18 +00003429Error
3430NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3431{
Todd Fiala75f47c32014-10-11 21:42:09 +00003432 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00003433
3434 Error error;
3435
3436 // Get a linux thread pointer.
3437 if (!thread_sp)
3438 {
3439 error.SetErrorString ("null thread_sp");
3440 if (log)
3441 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3442 return error;
3443 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003444 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00003445
3446 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003447 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003448 if (!context_sp)
3449 {
3450 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3451 if (log)
3452 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3453 return error;
3454 }
3455
3456 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003457 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00003458 if (error.Fail ())
3459 {
3460 if (log)
3461 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3462 return error;
3463 }
3464 else
3465 {
3466 if (log)
3467 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3468 }
3469
3470 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3471 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3472 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003473 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00003474 {
3475 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003476 if (breakpoint_addr >= breakpoint_size)
3477 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00003478 }
3479
3480 // Check if we stopped because of a breakpoint.
3481 NativeBreakpointSP breakpoint_sp;
3482 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3483 if (!error.Success () || !breakpoint_sp)
3484 {
3485 // We didn't find one at a software probe location. Nothing to do.
3486 if (log)
3487 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3488 return Error ();
3489 }
3490
3491 // If the breakpoint is not a software breakpoint, nothing to do.
3492 if (!breakpoint_sp->IsSoftwareBreakpoint ())
3493 {
3494 if (log)
3495 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3496 return Error ();
3497 }
3498
3499 //
3500 // We have a software breakpoint and need to adjust the PC.
3501 //
3502
3503 // Sanity check.
3504 if (breakpoint_size == 0)
3505 {
3506 // Nothing to do! How did we get here?
3507 if (log)
3508 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);
3509 return Error ();
3510 }
3511
3512 // Change the program counter.
3513 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003514 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 +00003515
3516 error = context_sp->SetPC (breakpoint_addr);
3517 if (error.Fail ())
3518 {
3519 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003520 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 +00003521 return error;
3522 }
3523
3524 return error;
3525}
Chaoren Linfa03ad22015-02-03 01:50:42 +00003526
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003527Error
3528NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
3529{
3530 char maps_file_name[32];
3531 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
3532
3533 FileSpec maps_file_spec(maps_file_name, false);
3534 if (!maps_file_spec.Exists()) {
3535 file_spec.Clear();
3536 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
3537 }
3538
3539 FileSpec module_file_spec(module_path, true);
3540
3541 std::ifstream maps_file(maps_file_name);
3542 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
3543 StringRef maps_data(maps_data_str.c_str());
3544
3545 while (!maps_data.empty())
3546 {
3547 StringRef maps_row;
3548 std::tie(maps_row, maps_data) = maps_data.split('\n');
3549
3550 SmallVector<StringRef, 16> maps_columns;
3551 maps_row.split(maps_columns, StringRef(" "), -1, false);
3552
3553 if (maps_columns.size() >= 6)
3554 {
3555 file_spec.SetFile(maps_columns[5].str().c_str(), false);
3556 if (file_spec.GetFilename() == module_file_spec.GetFilename())
3557 return Error();
3558 }
3559 }
3560
3561 file_spec.Clear();
3562 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
3563 module_file_spec.GetFilename().AsCString(), GetID());
3564}
Pavel Labathc0765592015-05-06 10:46:34 +00003565
Pavel Labath5eb721e2015-05-07 08:30:31 +00003566Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003567NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003568 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003569 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003570 bool error_when_already_running)
3571{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003572 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003573
3574 if (log)
3575 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3576 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003577
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003578 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3579 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003580
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003581 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003582 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003583 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003584
3585 lldbassert(!(error_when_already_running && !is_stopped));
3586
Pavel Labathc0765592015-05-06 10:46:34 +00003587 if (!is_stopped)
3588 {
3589 // It's not an error, just a log, if the error_when_already_running flag is not set.
3590 // This covers cases where, for instance, we're just trying to resume all threads
3591 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003592 if (log)
3593 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3594 __FUNCTION__,
3595 tid);
3596 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003597 }
3598
3599 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003600 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003601 // this thread to stop. This is potentially a buggy situation since
3602 // we're ostensibly waiting for threads to stop before we send out the
3603 // pending notification, and here we are resuming one before we send
3604 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003605 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003606 {
Pavel Labath108c3252015-05-12 09:03:18 +00003607 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 +00003608 }
3609
3610 // Request a resume. We expect this to be synchronous and the system
3611 // to reflect it is running after this completes.
3612 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003613 if (error.Success())
3614 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003615 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003616 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003617 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003618 __FUNCTION__, tid, error.AsCString ());
3619 }
3620
Pavel Labath5eb721e2015-05-07 08:30:31 +00003621 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003622}
3623
3624//===----------------------------------------------------------------------===//
3625
3626void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003627NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003628{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003629 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003630
Pavel Labath5eb721e2015-05-07 08:30:31 +00003631 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003632 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003633 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003634 __FUNCTION__, triggering_tid);
3635 }
3636
Pavel Labath337f3eb2015-05-08 08:57:45 +00003637 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003638
Pavel Labath5eb721e2015-05-07 08:30:31 +00003639 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003640 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003641 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003642 }
3643}
3644
3645void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003646NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003647{
3648 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3649 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3651
3652 // Clear any temporary breakpoints we used to implement software single stepping.
3653 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3654 {
3655 Error error = RemoveBreakpoint (thread_info.second);
3656 if (error.Fail())
3657 if (log)
3658 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3659 __FUNCTION__, thread_info.first, error.AsCString());
3660 }
3661 m_threads_stepping_with_breakpoint.clear();
3662
3663 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003664 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3665 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003666 m_pending_notification_up.reset();
3667 }
3668}
3669
Pavel Labathc0765592015-05-06 10:46:34 +00003670void
3671NativeProcessLinux::RequestStopOnAllRunningThreads()
3672{
3673 // Request a stop for all the thread stops that need to be stopped
3674 // and are not already known to be stopped. Keep a list of all the
3675 // threads from which we still need to hear a stop reply.
3676
3677 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003678 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003679 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003680 // We only care about running threads
3681 if (StateIsStoppedState(thread_sp->GetState(), true))
3682 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003683
Pavel Labath108c3252015-05-12 09:03:18 +00003684 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3685 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003686 }
3687
3688 // Set the wait list to the set of tids for which we requested stops.
3689 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3690}
3691
Pavel Labathc0765592015-05-06 10:46:34 +00003692
Pavel Labath5eb721e2015-05-07 08:30:31 +00003693Error
3694NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003695{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003696 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3697
3698 if (log)
3699 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3700 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3701
Pavel Labathc0765592015-05-06 10:46:34 +00003702 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003703 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3704 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003705
3706 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003707 auto& context = thread_sp->GetThreadContext();
3708 const auto stop_was_requested = context.stop_requested;
3709 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003710
3711 // If we have a pending notification, remove this from the set.
3712 if (m_pending_notification_up)
3713 {
3714 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003715 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003716 }
3717
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003718 Error error;
3719 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003720 {
3721 // We can end up here if stop was initiated by LLGS but by this time a
3722 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003723 if (log)
3724 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003725 error = context.request_resume_function (tid, true);
3726 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003727 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003728 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3729 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003730 }
3731 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003732 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003733}
3734
3735void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003736NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003737{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003738 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3739 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003740 {
3741 // Yikes - we've already got a pending signal notification in progress.
3742 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003743 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 +00003744 __FUNCTION__,
3745 m_pending_notification_up->triggering_tid,
3746 notification_up->triggering_tid);
3747 }
3748 m_pending_notification_up = std::move(notification_up);
3749
Pavel Labath108c3252015-05-12 09:03:18 +00003750 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003751
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003752 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003753}
3754
3755void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003756NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003757{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003758 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3759
3760 if (log)
3761 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3762
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003763 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3764 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003765
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003766 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003767 {
3768 // We will need to wait for this new thread to stop as well before firing the
3769 // notification.
3770 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003771 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003772 }
3773}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003774
3775Error
3776NativeProcessLinux::DoOperation(Operation* op)
3777{
3778 m_monitor_up->DoOperation(op);
3779 return op->GetError();
3780}
3781
3782// Wrapper for ptrace to catch errors and log calls.
3783// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
3784long
3785NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
3786{
3787 long int result;
3788
3789 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3790
3791 PtraceDisplayBytes(req, data, data_size);
3792
3793 error.Clear();
3794 errno = 0;
3795 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
3796 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3797 else
3798 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3799
3800 if (result == -1)
3801 error.SetErrorToErrno();
3802
3803 if (log)
3804 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, result);
3805
3806 PtraceDisplayBytes(req, data, data_size);
3807
3808 if (log && error.GetError() != 0)
3809 {
3810 const char* str;
3811 switch (error.GetError())
3812 {
3813 case ESRCH: str = "ESRCH"; break;
3814 case EINVAL: str = "EINVAL"; break;
3815 case EBUSY: str = "EBUSY"; break;
3816 case EPERM: str = "EPERM"; break;
3817 default: str = error.AsCString();
3818 }
3819 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3820 }
3821
3822 return result;
3823}