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