forked from swiftlang/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNativeProcessLinux.cpp
2064 lines (1722 loc) · 69.5 KB
/
NativeProcessLinux.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- NativeProcessLinux.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "NativeProcessLinux.h"
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <unistd.h>
#include <fstream>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <unordered_map>
#include "NativeThreadLinux.h"
#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
#include "Plugins/Process/Utility/LinuxProcMaps.h"
#include "Procfs.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostProcess.h"
#include "lldb/Host/ProcessLaunchInfo.h"
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Host/common/NativeRegisterContext.h"
#include "lldb/Host/linux/Host.h"
#include "lldb/Host/linux/Ptrace.h"
#include "lldb/Host/linux/Uio.h"
#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StringExtractor.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Threading.h"
#include <linux/unistd.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#ifdef __aarch64__
#include <asm/hwcap.h>
#include <sys/auxv.h>
#endif
// Support hardware breakpoints in case it has not been defined
#ifndef TRAP_HWBKPT
#define TRAP_HWBKPT 4
#endif
#ifndef HWCAP2_MTE
#define HWCAP2_MTE (1 << 18)
#endif
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_linux;
using namespace llvm;
// Private bits we only need internally.
static bool ProcessVmReadvSupported() {
static bool is_supported;
static llvm::once_flag flag;
llvm::call_once(flag, [] {
Log *log = GetLog(POSIXLog::Process);
uint32_t source = 0x47424742;
uint32_t dest = 0;
struct iovec local, remote;
remote.iov_base = &source;
local.iov_base = &dest;
remote.iov_len = local.iov_len = sizeof source;
// We shall try if cross-process-memory reads work by attempting to read a
// value from our own process.
ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
is_supported = (res == sizeof(source) && source == dest);
if (is_supported)
LLDB_LOG(log,
"Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled.");
else
LLDB_LOG(log,
"syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.",
llvm::sys::StrError());
});
return is_supported;
}
static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Log *log = GetLog(POSIXLog::Process);
if (!log)
return;
if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
else
LLDB_LOG(log, "leaving STDIN as is");
if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
else
LLDB_LOG(log, "leaving STDOUT as is");
if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
else
LLDB_LOG(log, "leaving STDERR as is");
int i = 0;
for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
++args, ++i)
LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
}
static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
uint8_t *ptr = (uint8_t *)bytes;
const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
for (uint32_t i = 0; i < loop_count; i++) {
s.Printf("[%x]", *ptr);
ptr++;
}
}
static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Log *log = GetLog(POSIXLog::Ptrace);
if (!log)
return;
StreamString buf;
switch (req) {
case PTRACE_POKETEXT: {
DisplayBytes(buf, &data, 8);
LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
break;
}
case PTRACE_POKEDATA: {
DisplayBytes(buf, &data, 8);
LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
break;
}
case PTRACE_POKEUSER: {
DisplayBytes(buf, &data, 8);
LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
break;
}
case PTRACE_SETREGS: {
DisplayBytes(buf, data, data_size);
LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
break;
}
case PTRACE_SETFPREGS: {
DisplayBytes(buf, data, data_size);
LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
break;
}
case PTRACE_SETSIGINFO: {
DisplayBytes(buf, data, sizeof(siginfo_t));
LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
break;
}
case PTRACE_SETREGSET: {
// Extract iov_base from data, which is a pointer to the struct iovec
DisplayBytes(buf, *(void **)data, data_size);
LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
break;
}
default: {}
}
}
static constexpr unsigned k_ptrace_word_size = sizeof(void *);
static_assert(sizeof(long) >= k_ptrace_word_size,
"Size of long must be larger than ptrace word size");
// Simple helper function to ensure flags are enabled on the given file
// descriptor.
static Status EnsureFDFlags(int fd, int flags) {
Status error;
int status = fcntl(fd, F_GETFL);
if (status == -1) {
error = Status::FromErrno();
return error;
}
if (fcntl(fd, F_SETFL, status | flags) == -1) {
error = Status::FromErrno();
return error;
}
return error;
}
static llvm::Error AddPtraceScopeNote(llvm::Error original_error) {
Expected<int> ptrace_scope = GetPtraceScope();
if (auto E = ptrace_scope.takeError()) {
Log *log = GetLog(POSIXLog::Process);
LLDB_LOG(log, "error reading value of ptrace_scope: {0}", E);
// The original error is probably more interesting than not being able to
// read or interpret ptrace_scope.
return original_error;
}
// We only have suggestions to provide for 1-3.
switch (*ptrace_scope) {
case 1:
case 2:
return llvm::createStringError(
std::error_code(errno, std::generic_category()),
"The current value of ptrace_scope is %d, which can cause ptrace to "
"fail to attach to a running process. To fix this, run:\n"
"\tsudo sysctl -w kernel.yama.ptrace_scope=0\n"
"For more information, see: "
"https://www.kernel.org/doc/Documentation/security/Yama.txt.",
*ptrace_scope);
case 3:
return llvm::createStringError(
std::error_code(errno, std::generic_category()),
"The current value of ptrace_scope is 3, which will cause ptrace to "
"fail to attach to a running process. This value cannot be changed "
"without rebooting.\n"
"For more information, see: "
"https://www.kernel.org/doc/Documentation/security/Yama.txt.");
case 0:
default:
return original_error;
}
}
NativeProcessLinux::Manager::Manager(MainLoop &mainloop)
: NativeProcessProtocol::Manager(mainloop) {
Status status;
m_sigchld_handle = mainloop.RegisterSignal(
SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
assert(m_sigchld_handle && status.Success());
}
llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
NativeProcessLinux::Manager::Launch(ProcessLaunchInfo &launch_info,
NativeDelegate &native_delegate) {
Log *log = GetLog(POSIXLog::Process);
MaybeLogLaunchInfo(launch_info);
Status status;
::pid_t pid = ProcessLauncherPosixFork()
.LaunchProcess(launch_info, status)
.GetProcessId();
LLDB_LOG(log, "pid = {0:x}", pid);
if (status.Fail()) {
LLDB_LOG(log, "failed to launch process: {0}", status);
return status.ToError();
}
// Wait for the child process to trap on its call to execve.
int wstatus = 0;
::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
assert(wpid == pid);
UNUSED_IF_ASSERT_DISABLED(wpid);
if (!WIFSTOPPED(wstatus)) {
LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
WaitStatus::Decode(wstatus));
return llvm::make_error<StringError>("Could not sync with inferior process",
llvm::inconvertibleErrorCode());
}
LLDB_LOG(log, "inferior started, now in stopped state");
status = SetDefaultPtraceOpts(pid);
if (status.Fail()) {
LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
return status.ToError();
}
llvm::Expected<ArchSpec> arch_or =
NativeRegisterContextLinux::DetermineArchitecture(pid);
if (!arch_or)
return arch_or.takeError();
return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
*arch_or, *this, {pid}));
}
llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
NativeProcessLinux::Manager::Attach(
lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate) {
Log *log = GetLog(POSIXLog::Process);
LLDB_LOG(log, "pid = {0:x}", pid);
auto tids_or = NativeProcessLinux::Attach(pid);
if (!tids_or)
return tids_or.takeError();
ArrayRef<::pid_t> tids = *tids_or;
llvm::Expected<ArchSpec> arch_or =
NativeRegisterContextLinux::DetermineArchitecture(tids[0]);
if (!arch_or)
return arch_or.takeError();
return std::unique_ptr<NativeProcessLinux>(
new NativeProcessLinux(pid, -1, native_delegate, *arch_or, *this, tids));
}
NativeProcessLinux::Extension
NativeProcessLinux::Manager::GetSupportedExtensions() const {
NativeProcessLinux::Extension supported =
Extension::multiprocess | Extension::fork | Extension::vfork |
Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 |
Extension::siginfo_read;
#ifdef __aarch64__
// At this point we do not have a process so read auxv directly.
if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
supported |= Extension::memory_tagging;
#endif
return supported;
}
static std::optional<std::pair<lldb::pid_t, WaitStatus>> WaitPid() {
Log *log = GetLog(POSIXLog::Process);
int status;
::pid_t wait_pid = llvm::sys::RetryAfterSignal(
-1, ::waitpid, -1, &status, __WALL | __WNOTHREAD | WNOHANG);
if (wait_pid == 0)
return std::nullopt;
if (wait_pid == -1) {
Status error(errno, eErrorTypePOSIX);
LLDB_LOG(log, "waitpid(-1, &status, _) failed: {1}", error);
return std::nullopt;
}
WaitStatus wait_status = WaitStatus::Decode(status);
LLDB_LOG(log, "waitpid(-1, &status, _) = {0}, status = {1}", wait_pid,
wait_status);
return std::make_pair(wait_pid, wait_status);
}
void NativeProcessLinux::Manager::SigchldHandler() {
Log *log = GetLog(POSIXLog::Process);
while (true) {
auto wait_result = WaitPid();
if (!wait_result)
return;
lldb::pid_t pid = wait_result->first;
WaitStatus status = wait_result->second;
// Ask each process whether it wants to handle the event. Each event should
// be handled by exactly one process, but thread creation events require
// special handling.
// Thread creation consists of two events (one on the parent and one on the
// child thread) and they can arrive in any order nondeterministically. The
// parent event carries the information about the child thread, but not
// vice-versa. This means that if the child event arrives first, it may not
// be handled by any process (because it doesn't know the thread belongs to
// it).
bool handled = llvm::any_of(m_processes, [&](NativeProcessLinux *process) {
return process->TryHandleWaitStatus(pid, status);
});
if (!handled) {
if (status.type == WaitStatus::Stop && status.status == SIGSTOP) {
// Store the thread creation event for later collection.
m_unowned_threads.insert(pid);
} else {
LLDB_LOG(log, "Ignoring waitpid event {0} for pid {1}", status, pid);
}
}
}
}
void NativeProcessLinux::Manager::CollectThread(::pid_t tid) {
Log *log = GetLog(POSIXLog::Process);
if (m_unowned_threads.erase(tid))
return; // We've encountered this thread already.
// The TID is not tracked yet, let's wait for it to appear.
int status = -1;
LLDB_LOG(log,
"received clone event for tid {0}. tid not tracked yet, "
"waiting for it to appear...",
tid);
::pid_t wait_pid =
llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
// It's theoretically possible to get other events if the entire process was
// SIGKILLed before we got a chance to check this. In that case, we'll just
// clean everything up when we get the process exit event.
LLDB_LOG(log,
"waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",
tid, wait_pid, errno, WaitStatus::Decode(status));
}
// Public Instance Methods
NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
NativeDelegate &delegate,
const ArchSpec &arch, Manager &manager,
llvm::ArrayRef<::pid_t> tids)
: NativeProcessELF(pid, terminal_fd, delegate), m_manager(manager),
m_arch(arch), m_intel_pt_collector(*this) {
manager.AddProcess(*this);
if (m_terminal_fd != -1) {
Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
assert(status.Success());
}
for (const auto &tid : tids) {
NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
ThreadWasCreated(thread);
}
// Let our process instance know the thread has stopped.
SetCurrentThreadID(tids[0]);
SetState(StateType::eStateStopped, false);
}
llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Log *log = GetLog(POSIXLog::Process);
Status status;
// Use a map to keep track of the threads which we have attached/need to
// attach.
Host::TidMap tids_to_attach;
while (Host::FindProcessThreads(pid, tids_to_attach)) {
for (Host::TidMap::iterator it = tids_to_attach.begin();
it != tids_to_attach.end();) {
if (it->second == false) {
lldb::tid_t tid = it->first;
// Attach to the requested process.
// An attach will cause the thread to stop with a SIGSTOP.
if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
// No such thread. The thread may have exited. More error handling
// may be needed.
if (status.GetError() == ESRCH) {
it = tids_to_attach.erase(it);
continue;
}
if (status.GetError() == EPERM) {
// Depending on the value of ptrace_scope, we can return a different
// error that suggests how to fix it.
return AddPtraceScopeNote(status.ToError());
}
return status.ToError();
}
int wpid =
llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
// Need to use __WALL otherwise we receive an error with errno=ECHLD At
// this point we should have a thread stopped if waitpid succeeds.
if (wpid < 0) {
// No such thread. The thread may have exited. More error handling
// may be needed.
if (errno == ESRCH) {
it = tids_to_attach.erase(it);
continue;
}
return llvm::errorCodeToError(
std::error_code(errno, std::generic_category()));
}
if ((status = SetDefaultPtraceOpts(tid)).Fail())
return status.ToError();
LLDB_LOG(log, "adding tid = {0}", tid);
it->second = true;
}
// move the loop forward
++it;
}
}
size_t tid_count = tids_to_attach.size();
if (tid_count == 0)
return llvm::make_error<StringError>("No such process",
llvm::inconvertibleErrorCode());
std::vector<::pid_t> tids;
tids.reserve(tid_count);
for (const auto &p : tids_to_attach)
tids.push_back(p.first);
return std::move(tids);
}
Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
long ptrace_opts = 0;
// Have the child raise an event on exit. This is used to keep the child in
// limbo until it is destroyed.
ptrace_opts |= PTRACE_O_TRACEEXIT;
// Have the tracer trace threads which spawn in the inferior process.
ptrace_opts |= PTRACE_O_TRACECLONE;
// Have the tracer notify us before execve returns (needed to disable legacy
// SIGTRAP generation)
ptrace_opts |= PTRACE_O_TRACEEXEC;
// Have the tracer trace forked children.
ptrace_opts |= PTRACE_O_TRACEFORK;
// Have the tracer trace vforks.
ptrace_opts |= PTRACE_O_TRACEVFORK;
// Have the tracer trace vfork-done in order to restore breakpoints after
// the child finishes sharing memory.
ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
}
bool NativeProcessLinux::TryHandleWaitStatus(lldb::pid_t pid,
WaitStatus status) {
if (pid == GetID() &&
(status.type == WaitStatus::Exit || status.type == WaitStatus::Signal)) {
// The process exited. We're done monitoring. Report to delegate.
SetExitStatus(status, true);
return true;
}
if (NativeThreadLinux *thread = GetThreadByID(pid)) {
MonitorCallback(*thread, status);
return true;
}
return false;
}
void NativeProcessLinux::MonitorCallback(NativeThreadLinux &thread,
WaitStatus status) {
Log *log = GetLog(LLDBLog::Process);
// Certain activities differ based on whether the pid is the tid of the main
// thread.
const bool is_main_thread = (thread.GetID() == GetID());
// Handle when the thread exits.
if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
LLDB_LOG(log,
"got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}",
status, thread.GetID(), is_main_thread ? "is" : "is not",
GetState());
// This is a thread that exited. Ensure we're not tracking it anymore.
StopTrackingThread(thread);
assert(!is_main_thread && "Main thread exits handled elsewhere");
return;
}
siginfo_t info;
const auto info_err = GetSignalInfo(thread.GetID(), &info);
// Get details on the signal raised.
if (info_err.Success()) {
// We have retrieved the signal info. Dispatch appropriately.
if (info.si_signo == SIGTRAP)
MonitorSIGTRAP(info, thread);
else
MonitorSignal(info, thread);
} else {
if (info_err.GetError() == EINVAL) {
// This is a group stop reception for this tid. We can reach here if we
// reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
// triggering the group-stop mechanism. Normally receiving these would
// stop the process, pending a SIGCONT. Simulating this state in a
// debugger is hard and is generally not needed (one use case is
// debugging background task being managed by a shell). For general use,
// it is sufficient to stop the process in a signal-delivery stop which
// happens before the group stop. This done by MonitorSignal and works
// correctly for all signals.
LLDB_LOG(log,
"received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the "
"thread.",
GetID(), thread.GetID());
ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
} else {
// ptrace(GETSIGINFO) failed (but not due to group-stop).
// A return value of ESRCH means the thread/process has died in the mean
// time. This can (e.g.) happen when another thread does an exit_group(2)
// or the entire process get SIGKILLed.
// We can't do anything with this thread anymore, but we keep it around
// until we get the WIFEXITED event.
LLDB_LOG(log,
"GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
"{3}. Expecting WIFEXITED soon.",
thread.GetID(), info_err, status, is_main_thread);
}
}
}
void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
NativeThreadLinux &thread) {
Log *log = GetLog(POSIXLog::Process);
const bool is_main_thread = (thread.GetID() == GetID());
assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
switch (info.si_code) {
case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
// This can either mean a new thread or a new process spawned via
// clone(2) without SIGCHLD or CLONE_VFORK flag. Note that clone(2)
// can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
// of these flags are passed.
unsigned long event_message = 0;
if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
LLDB_LOG(log,
"pid {0} received clone() event but GetEventMessage failed "
"so we don't know the new pid/tid",
thread.GetID());
ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
} else {
MonitorClone(thread, event_message, info.si_code >> 8);
}
break;
}
case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
// Exec clears any pending notifications.
m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
// Remove all but the main thread here. Linux fork creates a new process
// which only copies the main thread.
LLDB_LOG(log, "exec received, stop tracking all but main thread");
llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
return t->GetID() != GetID();
});
assert(m_threads.size() == 1);
auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
SetCurrentThreadID(main_thread->GetID());
main_thread->SetStoppedByExec();
// Tell coordinator about the "new" (since exec) stopped main thread.
ThreadWasCreated(*main_thread);
// Let our delegate know we have just exec'd.
NotifyDidExec();
// Let the process know we're stopped.
StopRunningThreads(main_thread->GetID());
break;
}
case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
// The inferior process or one of its threads is about to exit. We don't
// want to do anything with the thread so we just resume it. In case we
// want to implement "break on thread exit" functionality, we would need to
// stop here.
unsigned long data = 0;
if (GetEventMessage(thread.GetID(), &data).Fail())
data = -1;
LLDB_LOG(log,
"received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
is_main_thread);
StateType state = thread.GetState();
if (!StateIsRunningState(state)) {
// Due to a kernel bug, we may sometimes get this stop after the inferior
// gets a SIGKILL. This confuses our state tracking logic in
// ResumeThread(), since normally, we should not be receiving any ptrace
// events while the inferior is stopped. This makes sure that the
// inferior is resumed and exits normally.
state = eStateRunning;
}
ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
if (is_main_thread) {
// Main thread report the read (WIFEXITED) event only after all threads in
// the process exit, so we need to stop tracking it here instead of in
// MonitorCallback
StopTrackingThread(thread);
}
break;
}
case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
if (bool(m_enabled_extensions & Extension::vfork)) {
thread.SetStoppedByVForkDone();
StopRunningThreads(thread.GetID());
}
else
ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
break;
}
case 0:
case TRAP_TRACE: // We receive this on single stepping.
case TRAP_HWBKPT: // We receive this on watchpoint hit
{
// If a watchpoint was hit, report it
uint32_t wp_index;
Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
wp_index, (uintptr_t)info.si_addr);
if (error.Fail())
LLDB_LOG(log,
"received error while checking for watchpoint hits, pid = "
"{0}, error = {1}",
thread.GetID(), error);
if (wp_index != LLDB_INVALID_INDEX32) {
MonitorWatchpoint(thread, wp_index);
break;
}
// If a breakpoint was hit, report it
uint32_t bp_index;
error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
bp_index, (uintptr_t)info.si_addr);
if (error.Fail())
LLDB_LOG(log, "received error while checking for hardware "
"breakpoint hits, pid = {0}, error = {1}",
thread.GetID(), error);
if (bp_index != LLDB_INVALID_INDEX32) {
MonitorBreakpoint(thread);
break;
}
// Otherwise, report step over
MonitorTrace(thread);
break;
}
case SI_KERNEL:
#if defined __mips__
// For mips there is no special signal for watchpoint So we check for
// watchpoint in kernel trap
{
// If a watchpoint was hit, report it
uint32_t wp_index;
Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
wp_index, LLDB_INVALID_ADDRESS);
if (error.Fail())
LLDB_LOG(log,
"received error while checking for watchpoint hits, pid = "
"{0}, error = {1}",
thread.GetID(), error);
if (wp_index != LLDB_INVALID_INDEX32) {
MonitorWatchpoint(thread, wp_index);
break;
}
}
// NO BREAK
#endif
case TRAP_BRKPT:
MonitorBreakpoint(thread);
break;
case SIGTRAP:
case (SIGTRAP | 0x80):
LLDB_LOG(
log,
"received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
info.si_code, GetID(), thread.GetID());
// Ignore these signals until we know more about them.
ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
break;
default:
LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
info.si_code, GetID(), thread.GetID());
MonitorSignal(info, thread);
break;
}
}
void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Log *log = GetLog(POSIXLog::Process);
LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
// This thread is currently stopped.
thread.SetStoppedByTrace();
StopRunningThreads(thread.GetID());
}
void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
// Mark the thread as stopped at breakpoint.
thread.SetStoppedByBreakpoint();
FixupBreakpointPCAsNeeded(thread);
NativeRegisterContextLinux ®_ctx = thread.GetRegisterContext();
auto stepping_with_bp_it =
m_threads_stepping_with_breakpoint.find(thread.GetID());
if (stepping_with_bp_it != m_threads_stepping_with_breakpoint.end() &&
stepping_with_bp_it->second == reg_ctx.GetPC())
thread.SetStoppedByTrace();
StopRunningThreads(thread.GetID());
}
void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
uint32_t wp_index) {
Log *log = GetLog(LLDBLog::Process | LLDBLog::Watchpoints);
LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
thread.GetID(), wp_index);
// Mark the thread as stopped at watchpoint. The address is at
// (lldb::addr_t)info->si_addr if we need it.
thread.SetStoppedByWatchpoint(wp_index);
// We need to tell all other running threads before we notify the delegate
// about this stop.
StopRunningThreads(thread.GetID());
}
void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
NativeThreadLinux &thread) {
const int signo = info.si_signo;
const bool is_from_llgs = info.si_pid == getpid();
Log *log = GetLog(POSIXLog::Process);
// POSIX says that process behaviour is undefined after it ignores a SIGFPE,
// SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
// or raise(3). Similarly for tgkill(2) on Linux.
//
// IOW, user generated signals never generate what we consider to be a
// "crash".
//
// Similarly, ACK signals generated by this monitor.
// Handle the signal.
LLDB_LOG(log,
"received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})",
Host::GetSignalAsCString(signo), signo, info.si_code,
thread.GetID());
// Check for thread stop notification.
if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
// This is a tgkill()-based stop.
LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
// Check that we're not already marked with a stop reason. Note this thread
// really shouldn't already be marked as stopped - if we were, that would
// imply that the kernel signaled us with the thread stopping which we
// handled and marked as stopped, and that, without an intervening resume,
// we received another stop. It is more likely that we are missing the
// marking of a run state somewhere if we find that the thread was marked
// as stopped.
const StateType thread_state = thread.GetState();
if (!StateIsStoppedState(thread_state, false)) {
// An inferior thread has stopped because of a SIGSTOP we have sent it.
// Generally, these are not important stops and we don't want to report
// them as they are just used to stop other threads when one thread (the
// one with the *real* stop reason) hits a breakpoint (watchpoint,
// etc...). However, in the case of an asynchronous Interrupt(), this
// *is* the real stop reason, so we leave the signal intact if this is
// the thread that was chosen as the triggering thread.
if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
if (m_pending_notification_tid == thread.GetID())
thread.SetStoppedBySignal(SIGSTOP, &info);
else
thread.SetStoppedWithNoReason();
SetCurrentThreadID(thread.GetID());
SignalIfAllThreadsStopped();
} else {
// We can end up here if stop was initiated by LLGS but by this time a
// thread stop has occurred - maybe initiated by another event.
Status error = ResumeThread(thread, thread.GetState(), 0);
if (error.Fail())
LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
error);
}
} else {
LLDB_LOG(log,
"pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is",
GetID(), thread.GetID(), thread_state);
SignalIfAllThreadsStopped();
}
// Done handling.
return;
}
// Check if debugger should stop at this signal or just ignore it and resume
// the inferior.
if (m_signals_to_ignore.contains(signo)) {
ResumeThread(thread, thread.GetState(), signo);
return;
}
// This thread is stopped.
LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
thread.SetStoppedBySignal(signo, &info);
// Send a stop to the debugger after we get all other threads to stop.
StopRunningThreads(thread.GetID());
}
bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,
lldb::pid_t child_pid, int event) {
Log *log = GetLog(POSIXLog::Process);
LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
child_pid, event);
m_manager.CollectThread(child_pid);
switch (event) {
case PTRACE_EVENT_CLONE: {
// PTRACE_EVENT_CLONE can either mean a new thread or a new process.
// Try to grab the new process' PGID to figure out which one it is.
// If PGID is the same as the PID, then it's a new process. Otherwise,
// it's a thread.
auto tgid_ret = getPIDForTID(child_pid);
if (tgid_ret != child_pid) {
// A new thread should have PGID matching our process' PID.
assert(!tgid_ret || *tgid_ret == GetID());
NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
ThreadWasCreated(child_thread);
// Resume the parent.
ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
break;
}
}
[[fallthrough]];
case PTRACE_EVENT_FORK:
case PTRACE_EVENT_VFORK: {
bool is_vfork = event == PTRACE_EVENT_VFORK;
std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
m_manager, {static_cast<::pid_t>(child_pid)})};
if (!is_vfork)
child_process->m_software_breakpoints = m_software_breakpoints;
Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
if (bool(m_enabled_extensions & expected_ext)) {
m_delegate.NewSubprocess(this, std::move(child_process));
// NB: non-vfork clone() is reported as fork
parent.SetStoppedByFork(is_vfork, child_pid);
StopRunningThreads(parent.GetID());
} else {
child_process->Detach();
ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
}
break;
}
default:
llvm_unreachable("unknown clone_info.event");
}
return true;
}
bool NativeProcessLinux::SupportHardwareSingleStepping() const {