1 //===-- ProcessMonitor.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 <errno.h>
11 #include <poll.h>
12 #include <signal.h>
13 #include <stdint.h>
14 #include <string.h>
15 #include <sys/ptrace.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20
21 #include "lldb/Host/Host.h"
22 #include "lldb/Host/PseudoTerminal.h"
23 #include "lldb/Host/ThreadLauncher.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/Thread.h"
26 #include "lldb/Target/UnixSignals.h"
27 #include "lldb/Utility/RegisterValue.h"
28 #include "lldb/Utility/Scalar.h"
29 #include "lldb/Utility/Status.h"
30 #include "llvm/Support/Errno.h"
31
32 #include "FreeBSDThread.h"
33 #include "Plugins/Process/POSIX/CrashReason.h"
34 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
35 #include "ProcessFreeBSD.h"
36 #include "ProcessMonitor.h"
37
38 using namespace lldb;
39 using namespace lldb_private;
40
41 // We disable the tracing of ptrace calls for integration builds to avoid the
42 // additional indirection and checks.
43 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
44 // Wrapper for ptrace to catch errors and log calls.
45
Get_PT_IO_OP(int op)46 const char *Get_PT_IO_OP(int op) {
47 switch (op) {
48 case PIOD_READ_D:
49 return "READ_D";
50 case PIOD_WRITE_D:
51 return "WRITE_D";
52 case PIOD_READ_I:
53 return "READ_I";
54 case PIOD_WRITE_I:
55 return "WRITE_I";
56 default:
57 return "Unknown op";
58 }
59 }
60
61 // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
62 // errno on error because -1 is reserved as a valid result.
PtraceWrapper(int req,lldb::pid_t pid,void * addr,int data,const char * reqName,const char * file,int line)63 extern long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data,
64 const char *reqName, const char *file, int line) {
65 long int result;
66
67 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
68
69 if (log) {
70 log->Printf("ptrace(%s, %" PRIu64 ", %p, %x) called from file %s line %d",
71 reqName, pid, addr, data, file, line);
72 if (req == PT_IO) {
73 struct ptrace_io_desc *pi = (struct ptrace_io_desc *)addr;
74
75 log->Printf("PT_IO: op=%s offs=%zx size=%zu", Get_PT_IO_OP(pi->piod_op),
76 (size_t)pi->piod_offs, pi->piod_len);
77 }
78 }
79
80 // PtraceDisplayBytes(req, data);
81
82 errno = 0;
83 result = ptrace(req, pid, (caddr_t)addr, data);
84
85 // PtraceDisplayBytes(req, data);
86
87 if (log && errno != 0) {
88 const char *str;
89 switch (errno) {
90 case ESRCH:
91 str = "ESRCH";
92 break;
93 case EINVAL:
94 str = "EINVAL";
95 break;
96 case EBUSY:
97 str = "EBUSY";
98 break;
99 case EPERM:
100 str = "EPERM";
101 break;
102 default:
103 str = "<unknown>";
104 }
105 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
106 }
107
108 if (log) {
109 #ifdef __amd64__
110 if (req == PT_GETREGS) {
111 struct reg *r = (struct reg *)addr;
112
113 log->Printf("PT_GETREGS: rip=0x%lx rsp=0x%lx rbp=0x%lx rax=0x%lx",
114 r->r_rip, r->r_rsp, r->r_rbp, r->r_rax);
115 }
116 if (req == PT_GETDBREGS || req == PT_SETDBREGS) {
117 struct dbreg *r = (struct dbreg *)addr;
118 char setget = (req == PT_GETDBREGS) ? 'G' : 'S';
119
120 for (int i = 0; i <= 7; i++)
121 log->Printf("PT_%cETDBREGS: dr[%d]=0x%lx", setget, i, r->dr[i]);
122 }
123 #endif
124 }
125
126 return result;
127 }
128
129 // Wrapper for ptrace when logging is not required. Sets errno to 0 prior to
130 // calling ptrace.
PtraceWrapper(int req,lldb::pid_t pid,void * addr,int data)131 extern long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data) {
132 long result = 0;
133 errno = 0;
134 result = ptrace(req, pid, (caddr_t)addr, data);
135 return result;
136 }
137
138 #define PTRACE(req, pid, addr, data) \
139 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
140 #else
141 PtraceWrapper((req), (pid), (addr), (data))
142 #endif
143
144 //------------------------------------------------------------------------------
145 // Static implementations of ProcessMonitor::ReadMemory and
146 // ProcessMonitor::WriteMemory. This enables mutual recursion between these
147 // functions without needed to go thru the thread funnel.
148
DoReadMemory(lldb::pid_t pid,lldb::addr_t vm_addr,void * buf,size_t size,Status & error)149 static size_t DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf,
150 size_t size, Status &error) {
151 struct ptrace_io_desc pi_desc;
152
153 pi_desc.piod_op = PIOD_READ_D;
154 pi_desc.piod_offs = (void *)vm_addr;
155 pi_desc.piod_addr = buf;
156 pi_desc.piod_len = size;
157
158 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0) {
159 error.SetErrorToErrno();
160 return 0;
161 }
162 return pi_desc.piod_len;
163 }
164
DoWriteMemory(lldb::pid_t pid,lldb::addr_t vm_addr,const void * buf,size_t size,Status & error)165 static size_t DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr,
166 const void *buf, size_t size, Status &error) {
167 struct ptrace_io_desc pi_desc;
168
169 pi_desc.piod_op = PIOD_WRITE_D;
170 pi_desc.piod_offs = (void *)vm_addr;
171 pi_desc.piod_addr = (void *)buf;
172 pi_desc.piod_len = size;
173
174 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0) {
175 error.SetErrorToErrno();
176 return 0;
177 }
178 return pi_desc.piod_len;
179 }
180
181 // Simple helper function to ensure flags are enabled on the given file
182 // descriptor.
EnsureFDFlags(int fd,int flags,Status & error)183 static bool EnsureFDFlags(int fd, int flags, Status &error) {
184 int status;
185
186 if ((status = fcntl(fd, F_GETFL)) == -1) {
187 error.SetErrorToErrno();
188 return false;
189 }
190
191 if (fcntl(fd, F_SETFL, status | flags) == -1) {
192 error.SetErrorToErrno();
193 return false;
194 }
195
196 return true;
197 }
198
199 //------------------------------------------------------------------------------
200 /// @class Operation
201 /// Represents a ProcessMonitor operation.
202 ///
203 /// Under FreeBSD, it is not possible to ptrace() from any other thread but
204 /// the one that spawned or attached to the process from the start.
205 /// Therefore, when a ProcessMonitor is asked to deliver or change the state
206 /// of an inferior process the operation must be "funneled" to a specific
207 /// thread to perform the task. The Operation class provides an abstract base
208 /// for all services the ProcessMonitor must perform via the single virtual
209 /// function Execute, thus encapsulating the code that needs to run in the
210 /// privileged context.
211 class Operation {
212 public:
~Operation()213 virtual ~Operation() {}
214 virtual void Execute(ProcessMonitor *monitor) = 0;
215 };
216
217 //------------------------------------------------------------------------------
218 /// @class ReadOperation
219 /// Implements ProcessMonitor::ReadMemory.
220 class ReadOperation : public Operation {
221 public:
ReadOperation(lldb::addr_t addr,void * buff,size_t size,Status & error,size_t & result)222 ReadOperation(lldb::addr_t addr, void *buff, size_t size, Status &error,
223 size_t &result)
224 : m_addr(addr), m_buff(buff), m_size(size), m_error(error),
225 m_result(result) {}
226
227 void Execute(ProcessMonitor *monitor);
228
229 private:
230 lldb::addr_t m_addr;
231 void *m_buff;
232 size_t m_size;
233 Status &m_error;
234 size_t &m_result;
235 };
236
Execute(ProcessMonitor * monitor)237 void ReadOperation::Execute(ProcessMonitor *monitor) {
238 lldb::pid_t pid = monitor->GetPID();
239
240 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
241 }
242
243 //------------------------------------------------------------------------------
244 /// @class WriteOperation
245 /// Implements ProcessMonitor::WriteMemory.
246 class WriteOperation : public Operation {
247 public:
WriteOperation(lldb::addr_t addr,const void * buff,size_t size,Status & error,size_t & result)248 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
249 Status &error, size_t &result)
250 : m_addr(addr), m_buff(buff), m_size(size), m_error(error),
251 m_result(result) {}
252
253 void Execute(ProcessMonitor *monitor);
254
255 private:
256 lldb::addr_t m_addr;
257 const void *m_buff;
258 size_t m_size;
259 Status &m_error;
260 size_t &m_result;
261 };
262
Execute(ProcessMonitor * monitor)263 void WriteOperation::Execute(ProcessMonitor *monitor) {
264 lldb::pid_t pid = monitor->GetPID();
265
266 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
267 }
268
269 //------------------------------------------------------------------------------
270 /// @class ReadRegOperation
271 /// Implements ProcessMonitor::ReadRegisterValue.
272 class ReadRegOperation : public Operation {
273 public:
ReadRegOperation(lldb::tid_t tid,unsigned offset,unsigned size,RegisterValue & value,bool & result)274 ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
275 RegisterValue &value, bool &result)
276 : m_tid(tid), m_offset(offset), m_size(size), m_value(value),
277 m_result(result) {}
278
279 void Execute(ProcessMonitor *monitor);
280
281 private:
282 lldb::tid_t m_tid;
283 unsigned m_offset;
284 unsigned m_size;
285 RegisterValue &m_value;
286 bool &m_result;
287 };
288
Execute(ProcessMonitor * monitor)289 void ReadRegOperation::Execute(ProcessMonitor *monitor) {
290 struct reg regs;
291 int rc;
292
293 if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0)) < 0) {
294 m_result = false;
295 } else {
296 // 'struct reg' contains only 32- or 64-bit register values. Punt on
297 // others. Also, not all entries may be uintptr_t sized, such as 32-bit
298 // processes on powerpc64 (probably the same for i386 on amd64)
299 if (m_size == sizeof(uint32_t))
300 m_value = *(uint32_t *)(((caddr_t)®s) + m_offset);
301 else if (m_size == sizeof(uint64_t))
302 m_value = *(uint64_t *)(((caddr_t)®s) + m_offset);
303 else
304 memcpy((void *)&m_value, (((caddr_t)®s) + m_offset), m_size);
305 m_result = true;
306 }
307 }
308
309 //------------------------------------------------------------------------------
310 /// @class WriteRegOperation
311 /// Implements ProcessMonitor::WriteRegisterValue.
312 class WriteRegOperation : public Operation {
313 public:
WriteRegOperation(lldb::tid_t tid,unsigned offset,const RegisterValue & value,bool & result)314 WriteRegOperation(lldb::tid_t tid, unsigned offset,
315 const RegisterValue &value, bool &result)
316 : m_tid(tid), m_offset(offset), m_value(value), m_result(result) {}
317
318 void Execute(ProcessMonitor *monitor);
319
320 private:
321 lldb::tid_t m_tid;
322 unsigned m_offset;
323 const RegisterValue &m_value;
324 bool &m_result;
325 };
326
Execute(ProcessMonitor * monitor)327 void WriteRegOperation::Execute(ProcessMonitor *monitor) {
328 struct reg regs;
329
330 if (PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0) < 0) {
331 m_result = false;
332 return;
333 }
334 *(uintptr_t *)(((caddr_t)®s) + m_offset) =
335 (uintptr_t)m_value.GetAsUInt64();
336 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)®s, 0) < 0)
337 m_result = false;
338 else
339 m_result = true;
340 }
341
342 //------------------------------------------------------------------------------
343 /// @class ReadDebugRegOperation
344 /// Implements ProcessMonitor::ReadDebugRegisterValue.
345 class ReadDebugRegOperation : public Operation {
346 public:
ReadDebugRegOperation(lldb::tid_t tid,unsigned offset,unsigned size,RegisterValue & value,bool & result)347 ReadDebugRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
348 RegisterValue &value, bool &result)
349 : m_tid(tid), m_offset(offset), m_size(size), m_value(value),
350 m_result(result) {}
351
352 void Execute(ProcessMonitor *monitor);
353
354 private:
355 lldb::tid_t m_tid;
356 unsigned m_offset;
357 unsigned m_size;
358 RegisterValue &m_value;
359 bool &m_result;
360 };
361
Execute(ProcessMonitor * monitor)362 void ReadDebugRegOperation::Execute(ProcessMonitor *monitor) {
363 struct dbreg regs;
364 int rc;
365
366 if ((rc = PTRACE(PT_GETDBREGS, m_tid, (caddr_t)®s, 0)) < 0) {
367 m_result = false;
368 } else {
369 if (m_size == sizeof(uintptr_t))
370 m_value = *(uintptr_t *)(((caddr_t)®s) + m_offset);
371 else
372 memcpy((void *)&m_value, (((caddr_t)®s) + m_offset), m_size);
373 m_result = true;
374 }
375 }
376
377 //------------------------------------------------------------------------------
378 /// @class WriteDebugRegOperation
379 /// Implements ProcessMonitor::WriteDebugRegisterValue.
380 class WriteDebugRegOperation : public Operation {
381 public:
WriteDebugRegOperation(lldb::tid_t tid,unsigned offset,const RegisterValue & value,bool & result)382 WriteDebugRegOperation(lldb::tid_t tid, unsigned offset,
383 const RegisterValue &value, bool &result)
384 : m_tid(tid), m_offset(offset), m_value(value), m_result(result) {}
385
386 void Execute(ProcessMonitor *monitor);
387
388 private:
389 lldb::tid_t m_tid;
390 unsigned m_offset;
391 const RegisterValue &m_value;
392 bool &m_result;
393 };
394
Execute(ProcessMonitor * monitor)395 void WriteDebugRegOperation::Execute(ProcessMonitor *monitor) {
396 struct dbreg regs;
397
398 if (PTRACE(PT_GETDBREGS, m_tid, (caddr_t)®s, 0) < 0) {
399 m_result = false;
400 return;
401 }
402 *(uintptr_t *)(((caddr_t)®s) + m_offset) =
403 (uintptr_t)m_value.GetAsUInt64();
404 if (PTRACE(PT_SETDBREGS, m_tid, (caddr_t)®s, 0) < 0)
405 m_result = false;
406 else
407 m_result = true;
408 }
409
410 //------------------------------------------------------------------------------
411 /// @class ReadGPROperation
412 /// Implements ProcessMonitor::ReadGPR.
413 class ReadGPROperation : public Operation {
414 public:
ReadGPROperation(lldb::tid_t tid,void * buf,bool & result)415 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
416 : m_tid(tid), m_buf(buf), m_result(result) {}
417
418 void Execute(ProcessMonitor *monitor);
419
420 private:
421 lldb::tid_t m_tid;
422 void *m_buf;
423 bool &m_result;
424 };
425
Execute(ProcessMonitor * monitor)426 void ReadGPROperation::Execute(ProcessMonitor *monitor) {
427 int rc;
428
429 errno = 0;
430 rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
431 if (errno != 0)
432 m_result = false;
433 else
434 m_result = true;
435 }
436
437 //------------------------------------------------------------------------------
438 /// @class ReadFPROperation
439 /// Implements ProcessMonitor::ReadFPR.
440 class ReadFPROperation : public Operation {
441 public:
ReadFPROperation(lldb::tid_t tid,void * buf,bool & result)442 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
443 : m_tid(tid), m_buf(buf), m_result(result) {}
444
445 void Execute(ProcessMonitor *monitor);
446
447 private:
448 lldb::tid_t m_tid;
449 void *m_buf;
450 bool &m_result;
451 };
452
Execute(ProcessMonitor * monitor)453 void ReadFPROperation::Execute(ProcessMonitor *monitor) {
454 if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
455 m_result = false;
456 else
457 m_result = true;
458 }
459
460 //------------------------------------------------------------------------------
461 /// @class WriteGPROperation
462 /// Implements ProcessMonitor::WriteGPR.
463 class WriteGPROperation : public Operation {
464 public:
WriteGPROperation(lldb::tid_t tid,void * buf,bool & result)465 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
466 : m_tid(tid), m_buf(buf), m_result(result) {}
467
468 void Execute(ProcessMonitor *monitor);
469
470 private:
471 lldb::tid_t m_tid;
472 void *m_buf;
473 bool &m_result;
474 };
475
Execute(ProcessMonitor * monitor)476 void WriteGPROperation::Execute(ProcessMonitor *monitor) {
477 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
478 m_result = false;
479 else
480 m_result = true;
481 }
482
483 //------------------------------------------------------------------------------
484 /// @class WriteFPROperation
485 /// Implements ProcessMonitor::WriteFPR.
486 class WriteFPROperation : public Operation {
487 public:
WriteFPROperation(lldb::tid_t tid,void * buf,bool & result)488 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
489 : m_tid(tid), m_buf(buf), m_result(result) {}
490
491 void Execute(ProcessMonitor *monitor);
492
493 private:
494 lldb::tid_t m_tid;
495 void *m_buf;
496 bool &m_result;
497 };
498
Execute(ProcessMonitor * monitor)499 void WriteFPROperation::Execute(ProcessMonitor *monitor) {
500 if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
501 m_result = false;
502 else
503 m_result = true;
504 }
505
506 //------------------------------------------------------------------------------
507 /// @class ResumeOperation
508 /// Implements ProcessMonitor::Resume.
509 class ResumeOperation : public Operation {
510 public:
ResumeOperation(uint32_t signo,bool & result)511 ResumeOperation(uint32_t signo, bool &result)
512 : m_signo(signo), m_result(result) {}
513
514 void Execute(ProcessMonitor *monitor);
515
516 private:
517 uint32_t m_signo;
518 bool &m_result;
519 };
520
Execute(ProcessMonitor * monitor)521 void ResumeOperation::Execute(ProcessMonitor *monitor) {
522 lldb::pid_t pid = monitor->GetPID();
523 int data = 0;
524
525 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
526 data = m_signo;
527
528 if (PTRACE(PT_CONTINUE, pid, (caddr_t)1, data)) {
529 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
530 LLDB_LOG(log, "ResumeOperation ({0}) failed: {1}", pid,
531 llvm::sys::StrError(errno));
532 m_result = false;
533 } else
534 m_result = true;
535 }
536
537 //------------------------------------------------------------------------------
538 /// @class SingleStepOperation
539 /// Implements ProcessMonitor::SingleStep.
540 class SingleStepOperation : public Operation {
541 public:
SingleStepOperation(uint32_t signo,bool & result)542 SingleStepOperation(uint32_t signo, bool &result)
543 : m_signo(signo), m_result(result) {}
544
545 void Execute(ProcessMonitor *monitor);
546
547 private:
548 uint32_t m_signo;
549 bool &m_result;
550 };
551
Execute(ProcessMonitor * monitor)552 void SingleStepOperation::Execute(ProcessMonitor *monitor) {
553 lldb::pid_t pid = monitor->GetPID();
554 int data = 0;
555
556 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
557 data = m_signo;
558
559 if (PTRACE(PT_STEP, pid, NULL, data))
560 m_result = false;
561 else
562 m_result = true;
563 }
564
565 //------------------------------------------------------------------------------
566 /// @class LwpInfoOperation
567 /// Implements ProcessMonitor::GetLwpInfo.
568 class LwpInfoOperation : public Operation {
569 public:
LwpInfoOperation(lldb::tid_t tid,void * info,bool & result,int & ptrace_err)570 LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
571 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) {}
572
573 void Execute(ProcessMonitor *monitor);
574
575 private:
576 lldb::tid_t m_tid;
577 void *m_info;
578 bool &m_result;
579 int &m_err;
580 };
581
Execute(ProcessMonitor * monitor)582 void LwpInfoOperation::Execute(ProcessMonitor *monitor) {
583 struct ptrace_lwpinfo plwp;
584
585 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
586 m_result = false;
587 m_err = errno;
588 } else {
589 memcpy(m_info, &plwp, sizeof(plwp));
590 m_result = true;
591 }
592 }
593
594 //------------------------------------------------------------------------------
595 /// @class ThreadSuspendOperation
596 /// Implements ProcessMonitor::ThreadSuspend.
597 class ThreadSuspendOperation : public Operation {
598 public:
ThreadSuspendOperation(lldb::tid_t tid,bool suspend,bool & result)599 ThreadSuspendOperation(lldb::tid_t tid, bool suspend, bool &result)
600 : m_tid(tid), m_suspend(suspend), m_result(result) {}
601
602 void Execute(ProcessMonitor *monitor);
603
604 private:
605 lldb::tid_t m_tid;
606 bool m_suspend;
607 bool &m_result;
608 };
609
Execute(ProcessMonitor * monitor)610 void ThreadSuspendOperation::Execute(ProcessMonitor *monitor) {
611 m_result = !PTRACE(m_suspend ? PT_SUSPEND : PT_RESUME, m_tid, NULL, 0);
612 }
613
614 //------------------------------------------------------------------------------
615 /// @class EventMessageOperation
616 /// Implements ProcessMonitor::GetEventMessage.
617 class EventMessageOperation : public Operation {
618 public:
EventMessageOperation(lldb::tid_t tid,unsigned long * message,bool & result)619 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
620 : m_tid(tid), m_message(message), m_result(result) {}
621
622 void Execute(ProcessMonitor *monitor);
623
624 private:
625 lldb::tid_t m_tid;
626 unsigned long *m_message;
627 bool &m_result;
628 };
629
Execute(ProcessMonitor * monitor)630 void EventMessageOperation::Execute(ProcessMonitor *monitor) {
631 struct ptrace_lwpinfo plwp;
632
633 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
634 m_result = false;
635 else {
636 if (plwp.pl_flags & PL_FLAG_FORKED) {
637 *m_message = plwp.pl_child_pid;
638 m_result = true;
639 } else
640 m_result = false;
641 }
642 }
643
644 //------------------------------------------------------------------------------
645 /// @class KillOperation
646 /// Implements ProcessMonitor::Kill.
647 class KillOperation : public Operation {
648 public:
KillOperation(bool & result)649 KillOperation(bool &result) : m_result(result) {}
650
651 void Execute(ProcessMonitor *monitor);
652
653 private:
654 bool &m_result;
655 };
656
Execute(ProcessMonitor * monitor)657 void KillOperation::Execute(ProcessMonitor *monitor) {
658 lldb::pid_t pid = monitor->GetPID();
659
660 if (PTRACE(PT_KILL, pid, NULL, 0))
661 m_result = false;
662 else
663 m_result = true;
664 }
665
666 //------------------------------------------------------------------------------
667 /// @class DetachOperation
668 /// Implements ProcessMonitor::Detach.
669 class DetachOperation : public Operation {
670 public:
DetachOperation(Status & result)671 DetachOperation(Status &result) : m_error(result) {}
672
673 void Execute(ProcessMonitor *monitor);
674
675 private:
676 Status &m_error;
677 };
678
Execute(ProcessMonitor * monitor)679 void DetachOperation::Execute(ProcessMonitor *monitor) {
680 lldb::pid_t pid = monitor->GetPID();
681
682 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
683 m_error.SetErrorToErrno();
684 }
685
OperationArgs(ProcessMonitor * monitor)686 ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
687 : m_monitor(monitor) {
688 sem_init(&m_semaphore, 0, 0);
689 }
690
~OperationArgs()691 ProcessMonitor::OperationArgs::~OperationArgs() { sem_destroy(&m_semaphore); }
692
LaunchArgs(ProcessMonitor * monitor,lldb_private::Module * module,char const ** argv,Environment env,const FileSpec & stdin_file_spec,const FileSpec & stdout_file_spec,const FileSpec & stderr_file_spec,const FileSpec & working_dir)693 ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
694 lldb_private::Module *module,
695 char const **argv, Environment env,
696 const FileSpec &stdin_file_spec,
697 const FileSpec &stdout_file_spec,
698 const FileSpec &stderr_file_spec,
699 const FileSpec &working_dir)
700 : OperationArgs(monitor), m_module(module), m_argv(argv),
701 m_env(std::move(env)), m_stdin_file_spec(stdin_file_spec),
702 m_stdout_file_spec(stdout_file_spec),
703 m_stderr_file_spec(stderr_file_spec), m_working_dir(working_dir) {}
704
~LaunchArgs()705 ProcessMonitor::LaunchArgs::~LaunchArgs() {}
706
AttachArgs(ProcessMonitor * monitor,lldb::pid_t pid)707 ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor, lldb::pid_t pid)
708 : OperationArgs(monitor), m_pid(pid) {}
709
~AttachArgs()710 ProcessMonitor::AttachArgs::~AttachArgs() {}
711
712 //------------------------------------------------------------------------------
713 /// The basic design of the ProcessMonitor is built around two threads.
714 ///
715 /// One thread (@see SignalThread) simply blocks on a call to waitpid()
716 /// looking for changes in the debugee state. When a change is detected a
717 /// ProcessMessage is sent to the associated ProcessFreeBSD instance. This
718 /// thread "drives" state changes in the debugger.
719 ///
720 /// The second thread (@see OperationThread) is responsible for two things 1)
721 /// launching or attaching to the inferior process, and then 2) servicing
722 /// operations such as register reads/writes, stepping, etc. See the comments
723 /// on the Operation class for more info as to why this is needed.
ProcessMonitor(ProcessFreeBSD * process,Module * module,const char * argv[],Environment env,const FileSpec & stdin_file_spec,const FileSpec & stdout_file_spec,const FileSpec & stderr_file_spec,const FileSpec & working_dir,const lldb_private::ProcessLaunchInfo &,lldb_private::Status & error)724 ProcessMonitor::ProcessMonitor(
725 ProcessFreeBSD *process, Module *module, const char *argv[],
726 Environment env, const FileSpec &stdin_file_spec,
727 const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec,
728 const FileSpec &working_dir,
729 const lldb_private::ProcessLaunchInfo & /* launch_info */,
730 lldb_private::Status &error)
731 : m_process(static_cast<ProcessFreeBSD *>(process)),
732 m_pid(LLDB_INVALID_PROCESS_ID), m_terminal_fd(-1), m_operation(0) {
733 using namespace std::placeholders;
734
735 std::unique_ptr<LaunchArgs> args(
736 new LaunchArgs(this, module, argv, std::move(env), stdin_file_spec,
737 stdout_file_spec, stderr_file_spec, working_dir));
738
739 sem_init(&m_operation_pending, 0, 0);
740 sem_init(&m_operation_done, 0, 0);
741
742 StartLaunchOpThread(args.get(), error);
743 if (!error.Success())
744 return;
745
746 if (llvm::sys::RetryAfterSignal(-1, sem_wait, &args->m_semaphore) == -1) {
747 error.SetErrorToErrno();
748 return;
749 }
750
751 // Check that the launch was a success.
752 if (!args->m_error.Success()) {
753 StopOpThread();
754 error = args->m_error;
755 return;
756 }
757
758 // Finally, start monitoring the child process for change in state.
759 m_monitor_thread = Host::StartMonitoringChildProcess(
760 std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4),
761 GetPID(), true);
762 if (!m_monitor_thread.IsJoinable()) {
763 error.SetErrorToGenericError();
764 error.SetErrorString("Process launch failed.");
765 return;
766 }
767 }
768
ProcessMonitor(ProcessFreeBSD * process,lldb::pid_t pid,lldb_private::Status & error)769 ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid,
770 lldb_private::Status &error)
771 : m_process(static_cast<ProcessFreeBSD *>(process)), m_pid(pid),
772 m_terminal_fd(-1), m_operation(0) {
773 using namespace std::placeholders;
774
775 sem_init(&m_operation_pending, 0, 0);
776 sem_init(&m_operation_done, 0, 0);
777
778 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
779
780 StartAttachOpThread(args.get(), error);
781 if (!error.Success())
782 return;
783
784 if (llvm::sys::RetryAfterSignal(-1, sem_wait, &args->m_semaphore) == -1) {
785 error.SetErrorToErrno();
786 return;
787 }
788
789 // Check that the attach was a success.
790 if (!args->m_error.Success()) {
791 StopOpThread();
792 error = args->m_error;
793 return;
794 }
795
796 // Finally, start monitoring the child process for change in state.
797 m_monitor_thread = Host::StartMonitoringChildProcess(
798 std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4),
799 GetPID(), true);
800 if (!m_monitor_thread.IsJoinable()) {
801 error.SetErrorToGenericError();
802 error.SetErrorString("Process attach failed.");
803 return;
804 }
805 }
806
~ProcessMonitor()807 ProcessMonitor::~ProcessMonitor() { StopMonitor(); }
808
809 //------------------------------------------------------------------------------
810 // Thread setup and tear down.
StartLaunchOpThread(LaunchArgs * args,Status & error)811 void ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Status &error) {
812 static const char *g_thread_name = "lldb.process.freebsd.operation";
813
814 if (m_operation_thread.IsJoinable())
815 return;
816
817 m_operation_thread =
818 ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
819 }
820
LaunchOpThread(void * arg)821 void *ProcessMonitor::LaunchOpThread(void *arg) {
822 LaunchArgs *args = static_cast<LaunchArgs *>(arg);
823
824 if (!Launch(args)) {
825 sem_post(&args->m_semaphore);
826 return NULL;
827 }
828
829 ServeOperation(args);
830 return NULL;
831 }
832
Launch(LaunchArgs * args)833 bool ProcessMonitor::Launch(LaunchArgs *args) {
834 ProcessMonitor *monitor = args->m_monitor;
835 ProcessFreeBSD &process = monitor->GetProcess();
836 const char **argv = args->m_argv;
837 const FileSpec &stdin_file_spec = args->m_stdin_file_spec;
838 const FileSpec &stdout_file_spec = args->m_stdout_file_spec;
839 const FileSpec &stderr_file_spec = args->m_stderr_file_spec;
840 const FileSpec &working_dir = args->m_working_dir;
841
842 PseudoTerminal terminal;
843 const size_t err_len = 1024;
844 char err_str[err_len];
845 ::pid_t pid;
846
847 // Propagate the environment if one is not supplied.
848 Environment::Envp envp =
849 (args->m_env.empty() ? Host::GetEnvironment() : args->m_env).getEnvp();
850
851 if ((pid = terminal.Fork(err_str, err_len)) == -1) {
852 args->m_error.SetErrorToGenericError();
853 args->m_error.SetErrorString("Process fork failed.");
854 goto FINISH;
855 }
856
857 // Recognized child exit status codes.
858 enum {
859 ePtraceFailed = 1,
860 eDupStdinFailed,
861 eDupStdoutFailed,
862 eDupStderrFailed,
863 eChdirFailed,
864 eExecFailed,
865 eSetGidFailed
866 };
867
868 // Child process.
869 if (pid == 0) {
870 // Trace this process.
871 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
872 exit(ePtraceFailed);
873
874 // terminal has already dupped the tty descriptors to stdin/out/err. This
875 // closes original fd from which they were copied (and avoids leaking
876 // descriptors to the debugged process.
877 terminal.CloseSlaveFileDescriptor();
878
879 // Do not inherit setgid powers.
880 if (setgid(getgid()) != 0)
881 exit(eSetGidFailed);
882
883 // Let us have our own process group.
884 setpgid(0, 0);
885
886 // Dup file descriptors if needed.
887 //
888 // FIXME: If two or more of the paths are the same we needlessly open
889 // the same file multiple times.
890 if (stdin_file_spec)
891 if (!DupDescriptor(stdin_file_spec, STDIN_FILENO, O_RDONLY))
892 exit(eDupStdinFailed);
893
894 if (stdout_file_spec)
895 if (!DupDescriptor(stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT))
896 exit(eDupStdoutFailed);
897
898 if (stderr_file_spec)
899 if (!DupDescriptor(stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT))
900 exit(eDupStderrFailed);
901
902 // Change working directory
903 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
904 exit(eChdirFailed);
905
906 // Execute. We should never return.
907 execve(argv[0], const_cast<char *const *>(argv), envp);
908 exit(eExecFailed);
909 }
910
911 // Wait for the child process to to trap on its call to execve.
912 ::pid_t wpid;
913 int status;
914 if ((wpid = waitpid(pid, &status, 0)) < 0) {
915 args->m_error.SetErrorToErrno();
916 goto FINISH;
917 } else if (WIFEXITED(status)) {
918 // open, dup or execve likely failed for some reason.
919 args->m_error.SetErrorToGenericError();
920 switch (WEXITSTATUS(status)) {
921 case ePtraceFailed:
922 args->m_error.SetErrorString("Child ptrace failed.");
923 break;
924 case eDupStdinFailed:
925 args->m_error.SetErrorString("Child open stdin failed.");
926 break;
927 case eDupStdoutFailed:
928 args->m_error.SetErrorString("Child open stdout failed.");
929 break;
930 case eDupStderrFailed:
931 args->m_error.SetErrorString("Child open stderr failed.");
932 break;
933 case eChdirFailed:
934 args->m_error.SetErrorString("Child failed to set working directory.");
935 break;
936 case eExecFailed:
937 args->m_error.SetErrorString("Child exec failed.");
938 break;
939 case eSetGidFailed:
940 args->m_error.SetErrorString("Child setgid failed.");
941 break;
942 default:
943 args->m_error.SetErrorString("Child returned unknown exit status.");
944 break;
945 }
946 goto FINISH;
947 }
948 assert(WIFSTOPPED(status) && wpid == (::pid_t)pid &&
949 "Could not sync with inferior process.");
950
951 #ifdef notyet
952 // Have the child raise an event on exit. This is used to keep the child in
953 // limbo until it is destroyed.
954 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0) {
955 args->m_error.SetErrorToErrno();
956 goto FINISH;
957 }
958 #endif
959 // Release the master terminal descriptor and pass it off to the
960 // ProcessMonitor instance. Similarly stash the inferior pid.
961 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
962 monitor->m_pid = pid;
963
964 // Set the terminal fd to be in non blocking mode (it simplifies the
965 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
966 // descriptor to read from).
967 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
968 goto FINISH;
969
970 process.SendMessage(ProcessMessage::Attach(pid));
971
972 FINISH:
973 return args->m_error.Success();
974 }
975
StartAttachOpThread(AttachArgs * args,lldb_private::Status & error)976 void ProcessMonitor::StartAttachOpThread(AttachArgs *args,
977 lldb_private::Status &error) {
978 static const char *g_thread_name = "lldb.process.freebsd.operation";
979
980 if (m_operation_thread.IsJoinable())
981 return;
982
983 m_operation_thread =
984 ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
985 }
986
AttachOpThread(void * arg)987 void *ProcessMonitor::AttachOpThread(void *arg) {
988 AttachArgs *args = static_cast<AttachArgs *>(arg);
989
990 Attach(args);
991
992 ServeOperation(args);
993 return NULL;
994 }
995
Attach(AttachArgs * args)996 void ProcessMonitor::Attach(AttachArgs *args) {
997 lldb::pid_t pid = args->m_pid;
998
999 ProcessMonitor *monitor = args->m_monitor;
1000 ProcessFreeBSD &process = monitor->GetProcess();
1001
1002 if (pid <= 1) {
1003 args->m_error.SetErrorToGenericError();
1004 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1005 return;
1006 }
1007
1008 // Attach to the requested process.
1009 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0) {
1010 args->m_error.SetErrorToErrno();
1011 return;
1012 }
1013
1014 int status;
1015 if ((status = waitpid(pid, NULL, 0)) < 0) {
1016 args->m_error.SetErrorToErrno();
1017 return;
1018 }
1019
1020 process.SendMessage(ProcessMessage::Attach(pid));
1021 }
1022
1023 size_t
GetCurrentThreadIDs(std::vector<lldb::tid_t> & thread_ids)1024 ProcessMonitor::GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids) {
1025 lwpid_t *tids;
1026 int tdcnt;
1027
1028 thread_ids.clear();
1029
1030 tdcnt = PTRACE(PT_GETNUMLWPS, m_pid, NULL, 0);
1031 if (tdcnt <= 0)
1032 return 0;
1033 tids = (lwpid_t *)malloc(tdcnt * sizeof(*tids));
1034 if (tids == NULL)
1035 return 0;
1036 if (PTRACE(PT_GETLWPLIST, m_pid, (void *)tids, tdcnt) < 0) {
1037 free(tids);
1038 return 0;
1039 }
1040 thread_ids = std::vector<lldb::tid_t>(tids, tids + tdcnt);
1041 free(tids);
1042 return thread_ids.size();
1043 }
1044
MonitorCallback(ProcessMonitor * monitor,lldb::pid_t pid,bool exited,int signal,int status)1045 bool ProcessMonitor::MonitorCallback(ProcessMonitor *monitor, lldb::pid_t pid,
1046 bool exited, int signal, int status) {
1047 ProcessMessage message;
1048 ProcessFreeBSD *process = monitor->m_process;
1049 assert(process);
1050 bool stop_monitoring;
1051 struct ptrace_lwpinfo plwp;
1052 int ptrace_err;
1053
1054 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1055
1056 if (exited) {
1057 if (log)
1058 log->Printf("ProcessMonitor::%s() got exit signal, tid = %" PRIu64,
1059 __FUNCTION__, pid);
1060 message = ProcessMessage::Exit(pid, status);
1061 process->SendMessage(message);
1062 return pid == process->GetID();
1063 }
1064
1065 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
1066 stop_monitoring = true; // pid is gone. Bail.
1067 else {
1068 switch (plwp.pl_siginfo.si_signo) {
1069 case SIGTRAP:
1070 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1071 break;
1072
1073 default:
1074 message = MonitorSignal(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1075 break;
1076 }
1077
1078 process->SendMessage(message);
1079 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1080 }
1081
1082 return stop_monitoring;
1083 }
1084
MonitorSIGTRAP(ProcessMonitor * monitor,const siginfo_t * info,lldb::tid_t tid)1085 ProcessMessage ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1086 const siginfo_t *info,
1087 lldb::tid_t tid) {
1088 ProcessMessage message;
1089
1090 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1091
1092 assert(monitor);
1093 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1094
1095 switch (info->si_code) {
1096 default:
1097 assert(false && "Unexpected SIGTRAP code!");
1098 break;
1099
1100 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */): {
1101 // The inferior process is about to exit. Maintain the process in a state
1102 // of "limbo" until we are explicitly commanded to detach, destroy, resume,
1103 // etc.
1104 unsigned long data = 0;
1105 if (!monitor->GetEventMessage(tid, &data))
1106 data = -1;
1107 if (log)
1108 log->Printf("ProcessMonitor::%s() received exit? event, data = %lx, tid "
1109 "= %" PRIu64,
1110 __FUNCTION__, data, tid);
1111 message = ProcessMessage::Limbo(tid, (data >> 8));
1112 break;
1113 }
1114
1115 case 0:
1116 case TRAP_TRACE:
1117 #ifdef TRAP_CAP
1118 // Map TRAP_CAP to a trace trap in the absense of a more specific handler.
1119 case TRAP_CAP:
1120 #endif
1121 if (log)
1122 log->Printf("ProcessMonitor::%s() received trace event, tid = %" PRIu64
1123 " : si_code = %d",
1124 __FUNCTION__, tid, info->si_code);
1125 message = ProcessMessage::Trace(tid);
1126 break;
1127
1128 case SI_KERNEL:
1129 case TRAP_BRKPT:
1130 if (monitor->m_process->IsSoftwareStepBreakpoint(tid)) {
1131 if (log)
1132 log->Printf("ProcessMonitor::%s() received sw single step breakpoint "
1133 "event, tid = %" PRIu64,
1134 __FUNCTION__, tid);
1135 message = ProcessMessage::Trace(tid);
1136 } else {
1137 if (log)
1138 log->Printf(
1139 "ProcessMonitor::%s() received breakpoint event, tid = %" PRIu64,
1140 __FUNCTION__, tid);
1141 message = ProcessMessage::Break(tid);
1142 }
1143 break;
1144 }
1145
1146 return message;
1147 }
1148
MonitorSignal(ProcessMonitor * monitor,const siginfo_t * info,lldb::tid_t tid)1149 ProcessMessage ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1150 const siginfo_t *info,
1151 lldb::tid_t tid) {
1152 ProcessMessage message;
1153 int signo = info->si_signo;
1154
1155 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1156
1157 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1158 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
1159 // or raise(3). Similarly for tgkill(2) on FreeBSD.
1160 //
1161 // IOW, user generated signals never generate what we consider to be a
1162 // "crash".
1163 //
1164 // Similarly, ACK signals generated by this monitor.
1165 if (info->si_code == SI_USER) {
1166 if (log)
1167 log->Printf(
1168 "ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1169 __FUNCTION__,
1170 monitor->m_process->GetUnixSignals()->GetSignalAsCString(signo),
1171 "SI_USER", info->si_pid);
1172 if (info->si_pid == getpid())
1173 return ProcessMessage::SignalDelivered(tid, signo);
1174 else
1175 return ProcessMessage::Signal(tid, signo);
1176 }
1177
1178 if (log)
1179 log->Printf(
1180 "ProcessMonitor::%s() received signal %s", __FUNCTION__,
1181 monitor->m_process->GetUnixSignals()->GetSignalAsCString(signo));
1182
1183 switch (signo) {
1184 case SIGSEGV:
1185 case SIGILL:
1186 case SIGFPE:
1187 case SIGBUS:
1188 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1189 const auto reason = GetCrashReason(*info);
1190 if (reason != CrashReason::eInvalidCrashReason) {
1191 return ProcessMessage::Crash(tid, reason, signo, fault_addr);
1192 } // else; Use atleast si_signo info for other si_code
1193 }
1194
1195 // Everything else is "normal" and does not require any special action on our
1196 // part.
1197 return ProcessMessage::Signal(tid, signo);
1198 }
1199
ServeOperation(OperationArgs * args)1200 void ProcessMonitor::ServeOperation(OperationArgs *args) {
1201 ProcessMonitor *monitor = args->m_monitor;
1202
1203 // We are finised with the arguments and are ready to go. Sync with the
1204 // parent thread and start serving operations on the inferior.
1205 sem_post(&args->m_semaphore);
1206
1207 for (;;) {
1208 // wait for next pending operation
1209 sem_wait(&monitor->m_operation_pending);
1210
1211 monitor->m_operation->Execute(monitor);
1212
1213 // notify calling thread that operation is complete
1214 sem_post(&monitor->m_operation_done);
1215 }
1216 }
1217
DoOperation(Operation * op)1218 void ProcessMonitor::DoOperation(Operation *op) {
1219 std::lock_guard<std::mutex> guard(m_operation_mutex);
1220
1221 m_operation = op;
1222
1223 // notify operation thread that an operation is ready to be processed
1224 sem_post(&m_operation_pending);
1225
1226 // wait for operation to complete
1227 sem_wait(&m_operation_done);
1228 }
1229
ReadMemory(lldb::addr_t vm_addr,void * buf,size_t size,Status & error)1230 size_t ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1231 Status &error) {
1232 size_t result;
1233 ReadOperation op(vm_addr, buf, size, error, result);
1234 DoOperation(&op);
1235 return result;
1236 }
1237
WriteMemory(lldb::addr_t vm_addr,const void * buf,size_t size,lldb_private::Status & error)1238 size_t ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf,
1239 size_t size, lldb_private::Status &error) {
1240 size_t result;
1241 WriteOperation op(vm_addr, buf, size, error, result);
1242 DoOperation(&op);
1243 return result;
1244 }
1245
ReadRegisterValue(lldb::tid_t tid,unsigned offset,const char * reg_name,unsigned size,RegisterValue & value)1246 bool ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset,
1247 const char *reg_name, unsigned size,
1248 RegisterValue &value) {
1249 bool result;
1250 ReadRegOperation op(tid, offset, size, value, result);
1251 DoOperation(&op);
1252 return result;
1253 }
1254
WriteRegisterValue(lldb::tid_t tid,unsigned offset,const char * reg_name,const RegisterValue & value)1255 bool ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1256 const char *reg_name,
1257 const RegisterValue &value) {
1258 bool result;
1259 WriteRegOperation op(tid, offset, value, result);
1260 DoOperation(&op);
1261 return result;
1262 }
1263
ReadDebugRegisterValue(lldb::tid_t tid,unsigned offset,const char * reg_name,unsigned size,lldb_private::RegisterValue & value)1264 bool ProcessMonitor::ReadDebugRegisterValue(
1265 lldb::tid_t tid, unsigned offset, const char *reg_name, unsigned size,
1266 lldb_private::RegisterValue &value) {
1267 bool result;
1268 ReadDebugRegOperation op(tid, offset, size, value, result);
1269 DoOperation(&op);
1270 return result;
1271 }
1272
WriteDebugRegisterValue(lldb::tid_t tid,unsigned offset,const char * reg_name,const lldb_private::RegisterValue & value)1273 bool ProcessMonitor::WriteDebugRegisterValue(
1274 lldb::tid_t tid, unsigned offset, const char *reg_name,
1275 const lldb_private::RegisterValue &value) {
1276 bool result;
1277 WriteDebugRegOperation op(tid, offset, value, result);
1278 DoOperation(&op);
1279 return result;
1280 }
1281
ReadGPR(lldb::tid_t tid,void * buf,size_t buf_size)1282 bool ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1283 bool result;
1284 ReadGPROperation op(tid, buf, result);
1285 DoOperation(&op);
1286 return result;
1287 }
1288
ReadFPR(lldb::tid_t tid,void * buf,size_t buf_size)1289 bool ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1290 bool result;
1291 ReadFPROperation op(tid, buf, result);
1292 DoOperation(&op);
1293 return result;
1294 }
1295
ReadRegisterSet(lldb::tid_t tid,void * buf,size_t buf_size,unsigned int regset)1296 bool ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf,
1297 size_t buf_size, unsigned int regset) {
1298 return false;
1299 }
1300
WriteGPR(lldb::tid_t tid,void * buf,size_t buf_size)1301 bool ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1302 bool result;
1303 WriteGPROperation op(tid, buf, result);
1304 DoOperation(&op);
1305 return result;
1306 }
1307
WriteFPR(lldb::tid_t tid,void * buf,size_t buf_size)1308 bool ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size) {
1309 bool result;
1310 WriteFPROperation op(tid, buf, result);
1311 DoOperation(&op);
1312 return result;
1313 }
1314
WriteRegisterSet(lldb::tid_t tid,void * buf,size_t buf_size,unsigned int regset)1315 bool ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf,
1316 size_t buf_size, unsigned int regset) {
1317 return false;
1318 }
1319
ReadThreadPointer(lldb::tid_t tid,lldb::addr_t & value)1320 bool ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value) {
1321 return false;
1322 }
1323
Resume(lldb::tid_t unused,uint32_t signo)1324 bool ProcessMonitor::Resume(lldb::tid_t unused, uint32_t signo) {
1325 bool result;
1326 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1327
1328 if (log) {
1329 const char *signame =
1330 m_process->GetUnixSignals()->GetSignalAsCString(signo);
1331 if (signame == nullptr)
1332 signame = "<none>";
1333 log->Printf("ProcessMonitor::%s() resuming pid %" PRIu64 " with signal %s",
1334 __FUNCTION__, GetPID(), signame);
1335 }
1336 ResumeOperation op(signo, result);
1337 DoOperation(&op);
1338 if (log)
1339 log->Printf("ProcessMonitor::%s() resuming result = %s", __FUNCTION__,
1340 result ? "true" : "false");
1341 return result;
1342 }
1343
SingleStep(lldb::tid_t unused,uint32_t signo)1344 bool ProcessMonitor::SingleStep(lldb::tid_t unused, uint32_t signo) {
1345 bool result;
1346 SingleStepOperation op(signo, result);
1347 DoOperation(&op);
1348 return result;
1349 }
1350
Kill()1351 bool ProcessMonitor::Kill() {
1352 bool result;
1353 KillOperation op(result);
1354 DoOperation(&op);
1355 return result;
1356 }
1357
GetLwpInfo(lldb::tid_t tid,void * lwpinfo,int & ptrace_err)1358 bool ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo,
1359 int &ptrace_err) {
1360 bool result;
1361 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
1362 DoOperation(&op);
1363 return result;
1364 }
1365
ThreadSuspend(lldb::tid_t tid,bool suspend)1366 bool ProcessMonitor::ThreadSuspend(lldb::tid_t tid, bool suspend) {
1367 bool result;
1368 ThreadSuspendOperation op(tid, suspend, result);
1369 DoOperation(&op);
1370 return result;
1371 }
1372
GetEventMessage(lldb::tid_t tid,unsigned long * message)1373 bool ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message) {
1374 bool result;
1375 EventMessageOperation op(tid, message, result);
1376 DoOperation(&op);
1377 return result;
1378 }
1379
Detach(lldb::tid_t tid)1380 lldb_private::Status ProcessMonitor::Detach(lldb::tid_t tid) {
1381 lldb_private::Status error;
1382 if (tid != LLDB_INVALID_THREAD_ID) {
1383 DetachOperation op(error);
1384 DoOperation(&op);
1385 }
1386 return error;
1387 }
1388
DupDescriptor(const FileSpec & file_spec,int fd,int flags)1389 bool ProcessMonitor::DupDescriptor(const FileSpec &file_spec, int fd,
1390 int flags) {
1391 int target_fd = open(file_spec.GetCString(), flags, 0666);
1392
1393 if (target_fd == -1)
1394 return false;
1395
1396 if (dup2(target_fd, fd) == -1)
1397 return false;
1398
1399 return (close(target_fd) == -1) ? false : true;
1400 }
1401
StopMonitoringChildProcess()1402 void ProcessMonitor::StopMonitoringChildProcess() {
1403 if (m_monitor_thread.IsJoinable()) {
1404 m_monitor_thread.Cancel();
1405 m_monitor_thread.Join(nullptr);
1406 m_monitor_thread.Reset();
1407 }
1408 }
1409
StopMonitor()1410 void ProcessMonitor::StopMonitor() {
1411 StopMonitoringChildProcess();
1412 StopOpThread();
1413 sem_destroy(&m_operation_pending);
1414 sem_destroy(&m_operation_done);
1415 if (m_terminal_fd >= 0) {
1416 close(m_terminal_fd);
1417 m_terminal_fd = -1;
1418 }
1419 }
1420
1421 // FIXME: On Linux, when a new thread is created, we receive to notifications,
1422 // (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the child
1423 // thread id as additional information, and (2) a SIGSTOP|SI_USER from the new
1424 // child thread indicating that it has is stopped because we attached. We have
1425 // no guarantee of the order in which these arrive, but we need both before we
1426 // are ready to proceed. We currently keep a list of threads which have sent
1427 // the initial SIGSTOP|SI_USER event. Then when we receive the
1428 // SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not
1429 // occurred we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1430 //
1431 // Right now, the above logic is in ProcessPOSIX, so we need a definition of
1432 // this function in the FreeBSD ProcessMonitor implementation even if it isn't
1433 // logically needed.
1434 //
1435 // We really should figure out what actually happens on FreeBSD and move the
1436 // Linux-specific logic out of ProcessPOSIX as needed.
1437
WaitForInitialTIDStop(lldb::tid_t tid)1438 bool ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid) { return true; }
1439
StopOpThread()1440 void ProcessMonitor::StopOpThread() {
1441 if (!m_operation_thread.IsJoinable())
1442 return;
1443
1444 m_operation_thread.Cancel();
1445 m_operation_thread.Join(nullptr);
1446 m_operation_thread.Reset();
1447 }
1448