Bug Summary

File:include/llvm/Support/Error.h
Warning:line 201, column 5
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name NativeProcessLinux.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D HAVE_ROUND -D LLDB_CONFIGURATION_RELEASE -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/lldb/source/Plugins/Process/Linux -I /build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/lldb/include -I /build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -I /usr/include/python2.7 -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/lldb/source/Plugins/Process/Linux -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp

1//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno(*__errno_location ()).h>
14#include <stdint.h>
15#include <string.h>
16#include <unistd.h>
17
18// C++ Includes
19#include <fstream>
20#include <mutex>
21#include <sstream>
22#include <string>
23#include <unordered_map>
24
25// Other libraries and framework includes
26#include "lldb/Core/EmulateInstruction.h"
27#include "lldb/Core/ModuleSpec.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Host/HostProcess.h"
30#include "lldb/Host/PseudoTerminal.h"
31#include "lldb/Host/ThreadLauncher.h"
32#include "lldb/Host/common/NativeBreakpoint.h"
33#include "lldb/Host/common/NativeRegisterContext.h"
34#include "lldb/Host/linux/Ptrace.h"
35#include "lldb/Host/linux/Uio.h"
36#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
37#include "lldb/Symbol/ObjectFile.h"
38#include "lldb/Target/Process.h"
39#include "lldb/Target/ProcessLaunchInfo.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Utility/LLDBAssert.h"
42#include "lldb/Utility/RegisterValue.h"
43#include "lldb/Utility/State.h"
44#include "lldb/Utility/Status.h"
45#include "lldb/Utility/StringExtractor.h"
46#include "llvm/Support/Errno.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
49
50#include "NativeThreadLinux.h"
51#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
52#include "Procfs.h"
53
54#include <linux/unistd.h>
55#include <sys/socket.h>
56#include <sys/syscall.h>
57#include <sys/types.h>
58#include <sys/user.h>
59#include <sys/wait.h>
60
61// Support hardware breakpoints in case it has not been defined
62#ifndef TRAP_HWBKPT4
63#define TRAP_HWBKPT4 4
64#endif
65
66using namespace lldb;
67using namespace lldb_private;
68using namespace lldb_private::process_linux;
69using namespace llvm;
70
71// Private bits we only need internally.
72
73static bool ProcessVmReadvSupported() {
74 static bool is_supported;
75 static llvm::once_flag flag;
76
77 llvm::call_once(flag, [] {
78 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
79
80 uint32_t source = 0x47424742;
81 uint32_t dest = 0;
82
83 struct iovec local, remote;
84 remote.iov_base = &source;
85 local.iov_base = &dest;
86 remote.iov_len = local.iov_len = sizeof source;
87
88 // We shall try if cross-process-memory reads work by attempting to read a
89 // value from our own process.
90 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91 is_supported = (res == sizeof(source) && source == dest);
92 if (is_supported)
93 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
94 "Detected kernel support for process_vm_readv syscall. "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
95 "Fast memory reads enabled.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
;
96 else
97 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
98 "syscall process_vm_readv failed (error: {0}). Fast memory "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
99 "reads disabled.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
100 llvm::sys::StrError())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
;
101 });
102
103 return is_supported;
104}
105
106namespace {
107void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
108 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
109 if (!log)
110 return;
111
112 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO0))
113 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDIN to '{0}'", action->GetFileSpec(
)); } while (0)
;
114 else
115 LLDB_LOG(log, "leaving STDIN as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDIN as is"); } while (0)
;
116
117 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO1))
118 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDOUT to '{0}'", action->GetFileSpec
()); } while (0)
;
119 else
120 LLDB_LOG(log, "leaving STDOUT as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDOUT as is"); } while (0)
;
121
122 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO2))
123 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDERR to '{0}'", action->GetFileSpec
()); } while (0)
;
124 else
125 LLDB_LOG(log, "leaving STDERR as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDERR as is"); } while (0)
;
126
127 int i = 0;
128 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129 ++args, ++i)
130 LLDB_LOG(log, "arg {0}: '{1}'", i, *args)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "arg {0}: '{1}'", i, *args); } while (0)
;
131}
132
133void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134 uint8_t *ptr = (uint8_t *)bytes;
135 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES20, count);
136 for (uint32_t i = 0; i < loop_count; i++) {
137 s.Printf("[%x]", *ptr);
138 ptr++;
139 }
140}
141
142void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
143 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
144 if (!log)
145 return;
146 StreamString buf;
147
148 switch (req) {
149 case PTRACE_POKETEXT: {
150 DisplayBytes(buf, &data, 8);
151 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_POKETEXT {0}", buf.GetData()); } while (0
)
;
152 break;
153 }
154 case PTRACE_POKEDATA: {
155 DisplayBytes(buf, &data, 8);
156 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_POKEDATA {0}", buf.GetData()); } while (0
)
;
157 break;
158 }
159 case PTRACE_POKEUSER: {
160 DisplayBytes(buf, &data, 8);
161 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_POKEUSER {0}", buf.GetData()); } while (0
)
;
162 break;
163 }
164 case PTRACE_SETREGS13: {
165 DisplayBytes(buf, data, data_size);
166 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_SETREGS {0}", buf.GetData()); } while (0)
;
167 break;
168 }
169 case PTRACE_SETFPREGS15: {
170 DisplayBytes(buf, data, data_size);
171 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_SETFPREGS {0}", buf.GetData()); } while (
0)
;
172 break;
173 }
174 case PTRACE_SETSIGINFO: {
175 DisplayBytes(buf, data, sizeof(siginfo_t));
176 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_SETSIGINFO {0}", buf.GetData()); } while (
0)
;
177 break;
178 }
179 case PTRACE_SETREGSETPTRACE_SETREGSET: {
180 // Extract iov_base from data, which is a pointer to the struct iovec
181 DisplayBytes(buf, *(void **)data, data_size);
182 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "PTRACE_SETREGSET {0}", buf.GetData()); } while (
0)
;
183 break;
184 }
185 default: {}
186 }
187}
188
189static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190static_assert(sizeof(long) >= k_ptrace_word_size,
191 "Size of long must be larger than ptrace word size");
192} // end of anonymous namespace
193
194// Simple helper function to ensure flags are enabled on the given file
195// descriptor.
196static Status EnsureFDFlags(int fd, int flags) {
197 Status error;
198
199 int status = fcntl(fd, F_GETFL3);
200 if (status == -1) {
201 error.SetErrorToErrno();
202 return error;
203 }
204
205 if (fcntl(fd, F_SETFL4, status | flags) == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 return error;
211}
212
213// -----------------------------------------------------------------------------
214// Public Static Methods
215// -----------------------------------------------------------------------------
216
217llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
218NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
219 NativeDelegate &native_delegate,
220 MainLoop &mainloop) const {
221 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
222
223 MaybeLogLaunchInfo(launch_info);
224
225 Status status;
226 ::pid_t pid = ProcessLauncherPosixFork()
227 .LaunchProcess(launch_info, status)
228 .GetProcessId();
229 LLDB_LOG(log, "pid = {0:x}", pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}", pid); } while (0)
;
230 if (status.Fail()) {
231 LLDB_LOG(log, "failed to launch process: {0}", status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to launch process: {0}", status); } while
(0)
;
232 return status.ToError();
233 }
234
235 // Wait for the child process to trap on its call to execve.
236 int wstatus;
237 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
238 assert(wpid == pid)((wpid == pid) ? static_cast<void> (0) : __assert_fail (
"wpid == pid", "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 238, __PRETTY_FUNCTION__))
;
239 (void)wpid;
240 if (!WIFSTOPPED(wstatus)(((wstatus) & 0xff) == 0x7f)) {
241 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Could not sync with inferior process: wstatus={1}"
, WaitStatus::Decode(wstatus)); } while (0)
242 WaitStatus::Decode(wstatus))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Could not sync with inferior process: wstatus={1}"
, WaitStatus::Decode(wstatus)); } while (0)
;
243 return llvm::make_error<StringError>("Could not sync with inferior process",
244 llvm::inconvertibleErrorCode());
245 }
246 LLDB_LOG(log, "inferior started, now in stopped state")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "inferior started, now in stopped state"); } while
(0)
;
247
248 ProcessInstanceInfo Info;
249 if (!Host::GetProcessInfo(pid, Info)) {
250 return llvm::make_error<StringError>("Cannot get process architecture",
251 llvm::inconvertibleErrorCode());
252 }
253
254 // Set the architecture to the exe architecture.
255 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}, detected architecture {1}", pid, Info
.GetArchitecture().GetArchitectureName()); } while (0)
256 Info.GetArchitecture().GetArchitectureName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}, detected architecture {1}", pid, Info
.GetArchitecture().GetArchitectureName()); } while (0)
;
257
258 status = SetDefaultPtraceOpts(pid);
259 if (status.Fail()) {
260 LLDB_LOG(log, "failed to set default ptrace options: {0}", status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to set default ptrace options: {0}", status
); } while (0)
;
261 return status.ToError();
262 }
263
264 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
265 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
266 Info.GetArchitecture(), mainloop, {pid}));
267}
268
269llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
270NativeProcessLinux::Factory::Attach(
271 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
272 MainLoop &mainloop) const {
273 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
274 LLDB_LOG(log, "pid = {0:x}", pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}", pid); } while (0)
;
275
276 // Retrieve the architecture for the running process.
277 ProcessInstanceInfo Info;
278 if (!Host::GetProcessInfo(pid, Info)) {
1
Assuming the condition is true
2
Taking true branch
279 return llvm::make_error<StringError>("Cannot get process architecture",
3
Calling 'make_error<llvm::StringError, char const (&)[32], std::error_code>'
280 llvm::inconvertibleErrorCode());
281 }
282
283 auto tids_or = NativeProcessLinux::Attach(pid);
284 if (!tids_or)
285 return tids_or.takeError();
286
287 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
288 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
289}
290
291// -----------------------------------------------------------------------------
292// Public Instance Methods
293// -----------------------------------------------------------------------------
294
295NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
296 NativeDelegate &delegate,
297 const ArchSpec &arch, MainLoop &mainloop,
298 llvm::ArrayRef<::pid_t> tids)
299 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
300 if (m_terminal_fd != -1) {
301 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK04000);
302 assert(status.Success())((status.Success()) ? static_cast<void> (0) : __assert_fail
("status.Success()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 302, __PRETTY_FUNCTION__))
;
303 }
304
305 Status status;
306 m_sigchld_handle = mainloop.RegisterSignal(
307 SIGCHLD17, [this](MainLoopBase &) { SigchldHandler(); }, status);
308 assert(m_sigchld_handle && status.Success())((m_sigchld_handle && status.Success()) ? static_cast
<void> (0) : __assert_fail ("m_sigchld_handle && status.Success()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 308, __PRETTY_FUNCTION__))
;
309
310 for (const auto &tid : tids) {
311 NativeThreadLinux &thread = AddThread(tid);
312 thread.SetStoppedBySignal(SIGSTOP19);
313 ThreadWasCreated(thread);
314 }
315
316 // Let our process instance know the thread has stopped.
317 SetCurrentThreadID(tids[0]);
318 SetState(StateType::eStateStopped, false);
319
320 // Proccess any signals we received before installing our handler
321 SigchldHandler();
322}
323
324llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
325 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
326
327 Status status;
328 // Use a map to keep track of the threads which we have attached/need to
329 // attach.
330 Host::TidMap tids_to_attach;
331 while (Host::FindProcessThreads(pid, tids_to_attach)) {
332 for (Host::TidMap::iterator it = tids_to_attach.begin();
333 it != tids_to_attach.end();) {
334 if (it->second == false) {
335 lldb::tid_t tid = it->first;
336
337 // Attach to the requested process.
338 // An attach will cause the thread to stop with a SIGSTOP.
339 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
340 // No such thread. The thread may have exited. More error handling
341 // may be needed.
342 if (status.GetError() == ESRCH3) {
343 it = tids_to_attach.erase(it);
344 continue;
345 }
346 return status.ToError();
347 }
348
349 int wpid =
350 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL0x40000000);
351 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
352 // this point we should have a thread stopped if waitpid succeeds.
353 if (wpid < 0) {
354 // No such thread. The thread may have exited. More error handling
355 // may be needed.
356 if (errno(*__errno_location ()) == ESRCH3) {
357 it = tids_to_attach.erase(it);
358 continue;
359 }
360 return llvm::errorCodeToError(
361 std::error_code(errno(*__errno_location ()), std::generic_category()));
362 }
363
364 if ((status = SetDefaultPtraceOpts(tid)).Fail())
365 return status.ToError();
366
367 LLDB_LOG(log, "adding tid = {0}", tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "adding tid = {0}", tid); } while (0)
;
368 it->second = true;
369 }
370
371 // move the loop forward
372 ++it;
373 }
374 }
375
376 size_t tid_count = tids_to_attach.size();
377 if (tid_count == 0)
378 return llvm::make_error<StringError>("No such process",
379 llvm::inconvertibleErrorCode());
380
381 std::vector<::pid_t> tids;
382 tids.reserve(tid_count);
383 for (const auto &p : tids_to_attach)
384 tids.push_back(p.first);
385 return std::move(tids);
386}
387
388Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
389 long ptrace_opts = 0;
390
391 // Have the child raise an event on exit. This is used to keep the child in
392 // limbo until it is destroyed.
393 ptrace_opts |= PTRACE_O_TRACEEXIT;
394
395 // Have the tracer trace threads which spawn in the inferior process.
396 // TODO: if we want to support tracing the inferiors' child, add the
397 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
398 ptrace_opts |= PTRACE_O_TRACECLONE;
399
400 // Have the tracer notify us before execve returns (needed to disable legacy
401 // SIGTRAP generation)
402 ptrace_opts |= PTRACE_O_TRACEEXEC;
403
404 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
405}
406
407// Handles all waitpid events from the inferior process.
408void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
409 WaitStatus status) {
410 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1)));
411
412 // Certain activities differ based on whether the pid is the tid of the main
413 // thread.
414 const bool is_main_thread = (pid == GetID());
415
416 // Handle when the thread exits.
417 if (exited) {
418 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit signal({0}) , tid = {1} ({2} main thread), process "
"state = {3}", signal, pid, is_main_thread ? "is" : "is not"
, GetState()); } while (0)
419 "got exit signal({0}) , tid = {1} ({2} main thread), process "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit signal({0}) , tid = {1} ({2} main thread), process "
"state = {3}", signal, pid, is_main_thread ? "is" : "is not"
, GetState()); } while (0)
420 "state = {3}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit signal({0}) , tid = {1} ({2} main thread), process "
"state = {3}", signal, pid, is_main_thread ? "is" : "is not"
, GetState()); } while (0)
421 signal, pid, is_main_thread ? "is" : "is not", GetState())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit signal({0}) , tid = {1} ({2} main thread), process "
"state = {3}", signal, pid, is_main_thread ? "is" : "is not"
, GetState()); } while (0)
;
422
423 // This is a thread that exited. Ensure we're not tracking it anymore.
424 StopTrackingThread(pid);
425
426 if (is_main_thread) {
427 // The main thread exited. We're done monitoring. Report to delegate.
428 SetExitStatus(status, true);
429
430 // Notify delegate that our process has exited.
431 SetState(StateType::eStateExited, true);
432 }
433 return;
434 }
435
436 siginfo_t info;
437 const auto info_err = GetSignalInfo(pid, &info);
438 auto thread_sp = GetThreadByID(pid);
439
440 if (!thread_sp) {
441 // Normally, the only situation when we cannot find the thread is if we
442 // have just received a new thread notification. This is indicated by
443 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
444 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received notification about an unknown tid {0}."
, pid); } while (0)
;
445
446 if (info_err.Fail()) {
447 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "(tid {0}) GetSignalInfo failed ({1}). " "Ingoring this notification."
, pid, info_err); } while (0)
448 "(tid {0}) GetSignalInfo failed ({1}). "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "(tid {0}) GetSignalInfo failed ({1}). " "Ingoring this notification."
, pid, info_err); } while (0)
449 "Ingoring this notification.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "(tid {0}) GetSignalInfo failed ({1}). " "Ingoring this notification."
, pid, info_err); } while (0)
450 pid, info_err)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "(tid {0}) GetSignalInfo failed ({1}). " "Ingoring this notification."
, pid, info_err); } while (0)
;
451 return;
452 }
453
454 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code
, info._sifields._kill.si_pid); } while (0)
455 info.si_pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code
, info._sifields._kill.si_pid); } while (0)
;
456
457 NativeThreadLinux &thread = AddThread(pid);
458
459 // Resume the newly created thread.
460 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER(2147483647));
461 ThreadWasCreated(thread);
462 return;
463 }
464
465 // Get details on the signal raised.
466 if (info_err.Success()) {
467 // We have retrieved the signal info. Dispatch appropriately.
468 if (info.si_signo == SIGTRAP5)
469 MonitorSIGTRAP(info, *thread_sp);
470 else
471 MonitorSignal(info, *thread_sp, exited);
472 } else {
473 if (info_err.GetError() == EINVAL22) {
474 // This is a group stop reception for this tid. We can reach here if we
475 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
476 // triggering the group-stop mechanism. Normally receiving these would
477 // stop the process, pending a SIGCONT. Simulating this state in a
478 // debugger is hard and is generally not needed (one use case is
479 // debugging background task being managed by a shell). For general use,
480 // it is sufficient to stop the process in a signal-delivery stop which
481 // happens before the group stop. This done by MonitorSignal and works
482 // correctly for all signals.
483 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), pid); } while (0)
484 "received a group stop for pid {0} tid {1}. Transparent "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), pid); } while (0)
485 "handling of group stops not supported, resuming the "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), pid); } while (0)
486 "thread.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), pid); } while (0)
487 GetID(), pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), pid); } while (0)
;
488 ResumeThread(*thread_sp, thread_sp->GetState(),
489 LLDB_INVALID_SIGNAL_NUMBER(2147483647));
490 } else {
491 // ptrace(GETSIGINFO) failed (but not due to group-stop).
492
493 // A return value of ESRCH means the thread/process is no longer on the
494 // system, so it was killed somehow outside of our control. Either way,
495 // we can't do anything with it anymore.
496
497 // Stop tracking the metadata for the thread since it's entirely off the
498 // system now.
499 const bool thread_found = StopTrackingThread(pid);
500
501 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
"status = {3}, main_thread = {4}, thread_found: {5}", info_err
, pid, signal, status, is_main_thread, thread_found); } while
(0)
502 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
"status = {3}, main_thread = {4}, thread_found: {5}", info_err
, pid, signal, status, is_main_thread, thread_found); } while
(0)
503 "status = {3}, main_thread = {4}, thread_found: {5}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
"status = {3}, main_thread = {4}, thread_found: {5}", info_err
, pid, signal, status, is_main_thread, thread_found); } while
(0)
504 info_err, pid, signal, status, is_main_thread, thread_found)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
"status = {3}, main_thread = {4}, thread_found: {5}", info_err
, pid, signal, status, is_main_thread, thread_found); } while
(0)
;
505
506 if (is_main_thread) {
507 // Notify the delegate - our process is not available but appears to
508 // have been killed outside our control. Is eStateExited the right
509 // exit state in this case?
510 SetExitStatus(status, true);
511 SetState(StateType::eStateExited, true);
512 } else {
513 // This thread was pulled out from underneath us. Anything to do here?
514 // Do we want to do an all stop?
515 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1} non-main thread exit occurred, didn't "
"tell delegate anything since thread disappeared out " "from underneath us"
, GetID(), pid); } while (0)
516 "pid {0} tid {1} non-main thread exit occurred, didn't "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1} non-main thread exit occurred, didn't "
"tell delegate anything since thread disappeared out " "from underneath us"
, GetID(), pid); } while (0)
517 "tell delegate anything since thread disappeared out "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1} non-main thread exit occurred, didn't "
"tell delegate anything since thread disappeared out " "from underneath us"
, GetID(), pid); } while (0)
518 "from underneath us",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1} non-main thread exit occurred, didn't "
"tell delegate anything since thread disappeared out " "from underneath us"
, GetID(), pid); } while (0)
519 GetID(), pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1} non-main thread exit occurred, didn't "
"tell delegate anything since thread disappeared out " "from underneath us"
, GetID(), pid); } while (0)
;
520 }
521 }
522 }
523}
524
525void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
526 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
527
528 if (GetThreadByID(tid)) {
529 // We are already tracking the thread - we got the event on the new thread
530 // (see MonitorSignal) before this one. We are done.
531 return;
532 }
533
534 // The thread is not tracked yet, let's wait for it to appear.
535 int status = -1;
536 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received thread creation event for tid {0}. tid not tracked "
"yet, waiting for thread to appear...", tid); } while (0)
537 "received thread creation event for tid {0}. tid not tracked "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received thread creation event for tid {0}. tid not tracked "
"yet, waiting for thread to appear...", tid); } while (0)
538 "yet, waiting for thread to appear...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received thread creation event for tid {0}. tid not tracked "
"yet, waiting for thread to appear...", tid); } while (0)
539 tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received thread creation event for tid {0}. tid not tracked "
"yet, waiting for thread to appear...", tid); } while (0)
;
540 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL0x40000000);
541 // Since we are waiting on a specific tid, this must be the creation event.
542 // But let's do some checks just in case.
543 if (wait_pid != tid) {
544 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} failed. Assuming the thread has "
"disappeared in the meantime", tid); } while (0)
545 "waiting for tid {0} failed. Assuming the thread has "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} failed. Assuming the thread has "
"disappeared in the meantime", tid); } while (0)
546 "disappeared in the meantime",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} failed. Assuming the thread has "
"disappeared in the meantime", tid); } while (0)
547 tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} failed. Assuming the thread has "
"disappeared in the meantime", tid); } while (0)
;
548 // The only way I know of this could happen is if the whole process was
549 // SIGKILLed in the mean time. In any case, we can't do anything about that
550 // now.
551 return;
552 }
553 if (WIFEXITED(status)(((status) & 0x7f) == 0)) {
554 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} returned an 'exited' event. Not "
"tracking the thread.", tid); } while (0)
555 "waiting for tid {0} returned an 'exited' event. Not "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} returned an 'exited' event. Not "
"tracking the thread.", tid); } while (0)
556 "tracking the thread.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} returned an 'exited' event. Not "
"tracking the thread.", tid); } while (0)
557 tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waiting for tid {0} returned an 'exited' event. Not "
"tracking the thread.", tid); } while (0)
;
558 // Also a very improbable event.
559 return;
560 }
561
562 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0}: tracking new thread tid {1}", GetID()
, tid); } while (0)
;
563 NativeThreadLinux &new_thread = AddThread(tid);
564
565 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER(2147483647));
566 ThreadWasCreated(new_thread);
567}
568
569void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
570 NativeThreadLinux &thread) {
571 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
572 const bool is_main_thread = (thread.GetID() == GetID());
573
574 assert(info.si_signo == SIGTRAP && "Unexpected child signal!")((info.si_signo == 5 && "Unexpected child signal!") ?
static_cast<void> (0) : __assert_fail ("info.si_signo == SIGTRAP && \"Unexpected child signal!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 574, __PRETTY_FUNCTION__))
;
575
576 switch (info.si_code) {
577 // TODO: these two cases are required if we want to support tracing of the
578 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
579 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
580
581 case (SIGTRAP5 | (PTRACE_EVENT_CLONE << 8)): {
582 // This is the notification on the parent thread which informs us of new
583 // thread creation. We don't want to do anything with the parent thread so
584 // we just resume it. In case we want to implement "break on thread
585 // creation" functionality, we would need to stop here.
586
587 unsigned long event_message = 0;
588 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
589 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received thread creation event but " "GetEventMessage failed so we don't know the new tid"
, thread.GetID()); } while (0)
590 "pid {0} received thread creation event but "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received thread creation event but " "GetEventMessage failed so we don't know the new tid"
, thread.GetID()); } while (0)
591 "GetEventMessage failed so we don't know the new tid",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received thread creation event but " "GetEventMessage failed so we don't know the new tid"
, thread.GetID()); } while (0)
592 thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received thread creation event but " "GetEventMessage failed so we don't know the new tid"
, thread.GetID()); } while (0)
;
593 } else
594 WaitForNewThread(event_message);
595
596 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
597 break;
598 }
599
600 case (SIGTRAP5 | (PTRACE_EVENT_EXEC << 8)): {
601 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received exec event, code = {0}", info.si_code ^
5); } while (0)
;
602
603 // Exec clears any pending notifications.
604 m_pending_notification_tid = LLDB_INVALID_THREAD_ID0;
605
606 // Remove all but the main thread here. Linux fork creates a new process
607 // which only copies the main thread.
608 LLDB_LOG(log, "exec received, stop tracking all but main thread")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "exec received, stop tracking all but main thread"
); } while (0)
;
609
610 for (auto i = m_threads.begin(); i != m_threads.end();) {
611 if ((*i)->GetID() == GetID())
612 i = m_threads.erase(i);
613 else
614 ++i;
615 }
616 assert(m_threads.size() == 1)((m_threads.size() == 1) ? static_cast<void> (0) : __assert_fail
("m_threads.size() == 1", "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 616, __PRETTY_FUNCTION__))
;
617 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
618
619 SetCurrentThreadID(main_thread->GetID());
620 main_thread->SetStoppedByExec();
621
622 // Tell coordinator about about the "new" (since exec) stopped main thread.
623 ThreadWasCreated(*main_thread);
624
625 // Let our delegate know we have just exec'd.
626 NotifyDidExec();
627
628 // Let the process know we're stopped.
629 StopRunningThreads(main_thread->GetID());
630
631 break;
632 }
633
634 case (SIGTRAP5 | (PTRACE_EVENT_EXIT << 8)): {
635 // The inferior process or one of its threads is about to exit. We don't
636 // want to do anything with the thread so we just resume it. In case we
637 // want to implement "break on thread exit" functionality, we would need to
638 // stop here.
639
640 unsigned long data = 0;
641 if (GetEventMessage(thread.GetID(), &data).Fail())
642 data = -1;
643
644 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
645 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
646 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
647 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
648 is_main_thread)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
;
649
650
651 StateType state = thread.GetState();
652 if (!StateIsRunningState(state)) {
653 // Due to a kernel bug, we may sometimes get this stop after the inferior
654 // gets a SIGKILL. This confuses our state tracking logic in
655 // ResumeThread(), since normally, we should not be receiving any ptrace
656 // events while the inferior is stopped. This makes sure that the
657 // inferior is resumed and exits normally.
658 state = eStateRunning;
659 }
660 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER(2147483647));
661
662 break;
663 }
664
665 case 0:
666 case TRAP_TRACETRAP_TRACE: // We receive this on single stepping.
667 case TRAP_HWBKPT4: // We receive this on watchpoint hit
668 {
669 // If a watchpoint was hit, report it
670 uint32_t wp_index;
671 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
672 wp_index, (uintptr_t)info.si_addr_sifields._sigfault.si_addr);
673 if (error.Fail())
674 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
675 "received error while checking for watchpoint hits, pid = "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
676 "{0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
677 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
;
678 if (wp_index != LLDB_INVALID_INDEX32(4294967295U)) {
679 MonitorWatchpoint(thread, wp_index);
680 break;
681 }
682
683 // If a breakpoint was hit, report it
684 uint32_t bp_index;
685 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
686 bp_index, (uintptr_t)info.si_addr_sifields._sigfault.si_addr);
687 if (error.Fail())
688 LLDB_LOG(log, "received error while checking for hardware "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
689 "breakpoint hits, pid = {0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
690 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
;
691 if (bp_index != LLDB_INVALID_INDEX32(4294967295U)) {
692 MonitorBreakpoint(thread);
693 break;
694 }
695
696 // Otherwise, report step over
697 MonitorTrace(thread);
698 break;
699 }
700
701 case SI_KERNELSI_KERNEL:
702#if defined __mips__
703 // For mips there is no special signal for watchpoint So we check for
704 // watchpoint in kernel trap
705 {
706 // If a watchpoint was hit, report it
707 uint32_t wp_index;
708 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
709 wp_index, LLDB_INVALID_ADDRESS(18446744073709551615UL));
710 if (error.Fail())
711 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
712 "received error while checking for watchpoint hits, pid = "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
713 "{0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
714 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
;
715 if (wp_index != LLDB_INVALID_INDEX32(4294967295U)) {
716 MonitorWatchpoint(thread, wp_index);
717 break;
718 }
719 }
720// NO BREAK
721#endif
722 case TRAP_BRKPTTRAP_BRKPT:
723 MonitorBreakpoint(thread);
724 break;
725
726 case SIGTRAP5:
727 case (SIGTRAP5 | 0x80):
728 LLDB_LOG(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
729 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
730 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
731 info.si_code, GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
;
732
733 // Ignore these signals until we know more about them.
734 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
735 break;
736
737 default:
738 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}"
, info.si_code, GetID(), thread.GetID()); } while (0)
739 info.si_code, GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}"
, info.si_code, GetID(), thread.GetID()); } while (0)
;
740 MonitorSignal(info, thread, false);
741 break;
742 }
743}
744
745void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
746 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
747 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received trace event, pid = {0}", thread.GetID()
); } while (0)
;
748
749 // This thread is currently stopped.
750 thread.SetStoppedByTrace();
751
752 StopRunningThreads(thread.GetID());
753}
754
755void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
756 Log *log(
757 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1) | LIBLLDB_LOG_BREAKPOINTS(1u << 5)));
758 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received breakpoint event, pid = {0}", thread.GetID
()); } while (0)
;
759
760 // Mark the thread as stopped at breakpoint.
761 thread.SetStoppedByBreakpoint();
762 FixupBreakpointPCAsNeeded(thread);
763
764 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
765 m_threads_stepping_with_breakpoint.end())
766 thread.SetStoppedByTrace();
767
768 StopRunningThreads(thread.GetID());
769}
770
771void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
772 uint32_t wp_index) {
773 Log *log(
774 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1) | LIBLLDB_LOG_WATCHPOINTS(1u << 6)));
775 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received watchpoint event, pid = {0}, wp_index = {1}"
, thread.GetID(), wp_index); } while (0)
776 thread.GetID(), wp_index)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received watchpoint event, pid = {0}, wp_index = {1}"
, thread.GetID(), wp_index); } while (0)
;
777
778 // Mark the thread as stopped at watchpoint. The address is at
779 // (lldb::addr_t)info->si_addr if we need it.
780 thread.SetStoppedByWatchpoint(wp_index);
781
782 // We need to tell all other running threads before we notify the delegate
783 // about this stop.
784 StopRunningThreads(thread.GetID());
785}
786
787void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
788 NativeThreadLinux &thread, bool exited) {
789 const int signo = info.si_signo;
790 const bool is_from_llgs = info.si_pid_sifields._kill.si_pid == getpid();
791
792 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
793
794 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
795 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
796 // or raise(3). Similarly for tgkill(2) on Linux.
797 //
798 // IOW, user generated signals never generate what we consider to be a
799 // "crash".
800 //
801 // Similarly, ACK signals generated by this monitor.
802
803 // Handle the signal.
804 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
805 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
806 "waitpid pid = {4})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
807 Host::GetSignalAsCString(signo), signo, info.si_code,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
808 thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
;
809
810 // Check for thread stop notification.
811 if (is_from_llgs && (info.si_code == SI_TKILLSI_TKILL) && (signo == SIGSTOP19)) {
812 // This is a tgkill()-based stop.
813 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread stopped", GetID(), thread
.GetID()); } while (0)
;
814
815 // Check that we're not already marked with a stop reason. Note this thread
816 // really shouldn't already be marked as stopped - if we were, that would
817 // imply that the kernel signaled us with the thread stopping which we
818 // handled and marked as stopped, and that, without an intervening resume,
819 // we received another stop. It is more likely that we are missing the
820 // marking of a run state somewhere if we find that the thread was marked
821 // as stopped.
822 const StateType thread_state = thread.GetState();
823 if (!StateIsStoppedState(thread_state, false)) {
824 // An inferior thread has stopped because of a SIGSTOP we have sent it.
825 // Generally, these are not important stops and we don't want to report
826 // them as they are just used to stop other threads when one thread (the
827 // one with the *real* stop reason) hits a breakpoint (watchpoint,
828 // etc...). However, in the case of an asynchronous Interrupt(), this
829 // *is* the real stop reason, so we leave the signal intact if this is
830 // the thread that was chosen as the triggering thread.
831 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0) {
832 if (m_pending_notification_tid == thread.GetID())
833 thread.SetStoppedBySignal(SIGSTOP19, &info);
834 else
835 thread.SetStoppedWithNoReason();
836
837 SetCurrentThreadID(thread.GetID());
838 SignalIfAllThreadsStopped();
839 } else {
840 // We can end up here if stop was initiated by LLGS but by this time a
841 // thread stop has occurred - maybe initiated by another event.
842 Status error = ResumeThread(thread, thread.GetState(), 0);
843 if (error.Fail())
844 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to resume thread {0}: {1}", thread.GetID(
), error); } while (0)
845 error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to resume thread {0}: {1}", thread.GetID(
), error); } while (0)
;
846 }
847 } else {
848 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
849 "pid {0} tid {1}, thread was already marked as a stopped "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
850 "state (state={2}), leaving stop signal as is",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
851 GetID(), thread.GetID(), thread_state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
;
852 SignalIfAllThreadsStopped();
853 }
854
855 // Done handling.
856 return;
857 }
858
859 // Check if debugger should stop at this signal or just ignore it and resume
860 // the inferior.
861 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
862 ResumeThread(thread, thread.GetState(), signo);
863 return;
864 }
865
866 // This thread is stopped.
867 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0}", Host::GetSignalAsCString(signo
)); } while (0)
;
868 thread.SetStoppedBySignal(signo, &info);
869
870 // Send a stop to the debugger after we get all other threads to stop.
871 StopRunningThreads(thread.GetID());
872}
873
874namespace {
875
876struct EmulatorBaton {
877 NativeProcessLinux &m_process;
878 NativeRegisterContext &m_reg_context;
879
880 // eRegisterKindDWARF -> RegsiterValue
881 std::unordered_map<uint32_t, RegisterValue> m_register_values;
882
883 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
884 : m_process(process), m_reg_context(reg_context) {}
885};
886
887} // anonymous namespace
888
889static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
890 const EmulateInstruction::Context &context,
891 lldb::addr_t addr, void *dst, size_t length) {
892 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
893
894 size_t bytes_read;
895 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
896 return bytes_read;
897}
898
899static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
900 const RegisterInfo *reg_info,
901 RegisterValue &reg_value) {
902 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
903
904 auto it = emulator_baton->m_register_values.find(
905 reg_info->kinds[eRegisterKindDWARF]);
906 if (it != emulator_baton->m_register_values.end()) {
907 reg_value = it->second;
908 return true;
909 }
910
911 // The emulator only fill in the dwarf regsiter numbers (and in some case the
912 // generic register numbers). Get the full register info from the register
913 // context based on the dwarf register numbers.
914 const RegisterInfo *full_reg_info =
915 emulator_baton->m_reg_context.GetRegisterInfo(
916 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
917
918 Status error =
919 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
920 if (error.Success())
921 return true;
922
923 return false;
924}
925
926static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
927 const EmulateInstruction::Context &context,
928 const RegisterInfo *reg_info,
929 const RegisterValue &reg_value) {
930 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
931 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
932 reg_value;
933 return true;
934}
935
936static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
937 const EmulateInstruction::Context &context,
938 lldb::addr_t addr, const void *dst,
939 size_t length) {
940 return length;
941}
942
943static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
944 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
945 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS4);
946 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
947 LLDB_INVALID_ADDRESS(18446744073709551615UL));
948}
949
950Status
951NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
952 Status error;
953 NativeRegisterContext& register_context = thread.GetRegisterContext();
954
955 std::unique_ptr<EmulateInstruction> emulator_ap(
956 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
957 nullptr));
958
959 if (emulator_ap == nullptr)
960 return Status("Instruction emulator not found!");
961
962 EmulatorBaton baton(*this, register_context);
963 emulator_ap->SetBaton(&baton);
964 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
965 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
966 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
967 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
968
969 if (!emulator_ap->ReadInstruction())
970 return Status("Read instruction failed!");
971
972 bool emulation_result =
973 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
974
975 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
976 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC0);
977 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
978 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS4);
979
980 auto pc_it =
981 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
982 auto flags_it =
983 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
984
985 lldb::addr_t next_pc;
986 lldb::addr_t next_flags;
987 if (emulation_result) {
988 assert(pc_it != baton.m_register_values.end() &&((pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated"
) ? static_cast<void> (0) : __assert_fail ("pc_it != baton.m_register_values.end() && \"Emulation was successfull but PC wasn't updated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 989, __PRETTY_FUNCTION__))
989 "Emulation was successfull but PC wasn't updated")((pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated"
) ? static_cast<void> (0) : __assert_fail ("pc_it != baton.m_register_values.end() && \"Emulation was successfull but PC wasn't updated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 989, __PRETTY_FUNCTION__))
;
990 next_pc = pc_it->second.GetAsUInt64();
991
992 if (flags_it != baton.m_register_values.end())
993 next_flags = flags_it->second.GetAsUInt64();
994 else
995 next_flags = ReadFlags(register_context);
996 } else if (pc_it == baton.m_register_values.end()) {
997 // Emulate instruction failed and it haven't changed PC. Advance PC with
998 // the size of the current opcode because the emulation of all
999 // PC modifying instruction should be successful. The failure most
1000 // likely caused by a not supported instruction which don't modify PC.
1001 next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1002 next_flags = ReadFlags(register_context);
1003 } else {
1004 // The instruction emulation failed after it modified the PC. It is an
1005 // unknown error where we can't continue because the next instruction is
1006 // modifying the PC but we don't know how.
1007 return Status("Instruction emulation failed unexpectedly.");
1008 }
1009
1010 if (m_arch.GetMachine() == llvm::Triple::arm) {
1011 if (next_flags & 0x20) {
1012 // Thumb mode
1013 error = SetSoftwareBreakpoint(next_pc, 2);
1014 } else {
1015 // Arm mode
1016 error = SetSoftwareBreakpoint(next_pc, 4);
1017 }
1018 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1019 m_arch.GetMachine() == llvm::Triple::mips64el ||
1020 m_arch.GetMachine() == llvm::Triple::mips ||
1021 m_arch.GetMachine() == llvm::Triple::mipsel ||
1022 m_arch.GetMachine() == llvm::Triple::ppc64le)
1023 error = SetSoftwareBreakpoint(next_pc, 4);
1024 else {
1025 // No size hint is given for the next breakpoint
1026 error = SetSoftwareBreakpoint(next_pc, 0);
1027 }
1028
1029 // If setting the breakpoint fails because next_pc is out of the address
1030 // space, ignore it and let the debugee segfault.
1031 if (error.GetError() == EIO5 || error.GetError() == EFAULT14) {
1032 return Status();
1033 } else if (error.Fail())
1034 return error;
1035
1036 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1037
1038 return Status();
1039}
1040
1041bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1042 if (m_arch.GetMachine() == llvm::Triple::arm ||
1043 m_arch.GetMachine() == llvm::Triple::mips64 ||
1044 m_arch.GetMachine() == llvm::Triple::mips64el ||
1045 m_arch.GetMachine() == llvm::Triple::mips ||
1046 m_arch.GetMachine() == llvm::Triple::mipsel)
1047 return false;
1048 return true;
1049}
1050
1051Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1052 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1053 LLDB_LOG(log, "pid {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0}", GetID()); } while (0)
;
1054
1055 bool software_single_step = !SupportHardwareSingleStepping();
1056
1057 if (software_single_step) {
1058 for (const auto &thread : m_threads) {
1059 assert(thread && "thread list should not contain NULL threads")((thread && "thread list should not contain NULL threads"
) ? static_cast<void> (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1059, __PRETTY_FUNCTION__))
;
1060
1061 const ResumeAction *const action =
1062 resume_actions.GetActionForThread(thread->GetID(), true);
1063 if (action == nullptr)
1064 continue;
1065
1066 if (action->state == eStateStepping) {
1067 Status error = SetupSoftwareSingleStepping(
1068 static_cast<NativeThreadLinux &>(*thread));
1069 if (error.Fail())
1070 return error;
1071 }
1072 }
1073 }
1074
1075 for (const auto &thread : m_threads) {
1076 assert(thread && "thread list should not contain NULL threads")((thread && "thread list should not contain NULL threads"
) ? static_cast<void> (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1076, __PRETTY_FUNCTION__))
;
1077
1078 const ResumeAction *const action =
1079 resume_actions.GetActionForThread(thread->GetID(), true);
1080
1081 if (action == nullptr) {
1082 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "no action specified for pid {0} tid {1}", GetID(
), thread->GetID()); } while (0)
1083 thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "no action specified for pid {0} tid {1}", GetID(
), thread->GetID()); } while (0)
;
1084 continue;
1085 }
1086
1087 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "processing resume action state {0} for pid {1} tid {2}"
, action->state, GetID(), thread->GetID()); } while (0)
1088 action->state, GetID(), thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "processing resume action state {0} for pid {1} tid {2}"
, action->state, GetID(), thread->GetID()); } while (0)
;
1089
1090 switch (action->state) {
1091 case eStateRunning:
1092 case eStateStepping: {
1093 // Run the thread, possibly feeding it the signal.
1094 const int signo = action->signal;
1095 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1096 signo);
1097 break;
1098 }
1099
1100 case eStateSuspended:
1101 case eStateStopped:
1102 llvm_unreachable("Unexpected state")::llvm::llvm_unreachable_internal("Unexpected state", "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1102)
;
1103
1104 default:
1105 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1106 "for pid %" PRIu64"l" "u" ", tid %" PRIu64"l" "u",
1107 __FUNCTION__, StateAsCString(action->state), GetID(),
1108 thread->GetID());
1109 }
1110 }
1111
1112 return Status();
1113}
1114
1115Status NativeProcessLinux::Halt() {
1116 Status error;
1117
1118 if (kill(GetID(), SIGSTOP19) != 0)
1119 error.SetErrorToErrno();
1120
1121 return error;
1122}
1123
1124Status NativeProcessLinux::Detach() {
1125 Status error;
1126
1127 // Stop monitoring the inferior.
1128 m_sigchld_handle.reset();
1129
1130 // Tell ptrace to detach from the process.
1131 if (GetID() == LLDB_INVALID_PROCESS_ID0)
1132 return error;
1133
1134 for (const auto &thread : m_threads) {
1135 Status e = Detach(thread->GetID());
1136 if (e.Fail())
1137 error =
1138 e; // Save the error, but still attempt to detach from other threads.
1139 }
1140
1141 m_processor_trace_monitor.clear();
1142 m_pt_proces_trace_id = LLDB_INVALID_UID(18446744073709551615UL);
1143
1144 return error;
1145}
1146
1147Status NativeProcessLinux::Signal(int signo) {
1148 Status error;
1149
1150 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1151 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "sending signal {0} ({1}) to pid {1}", signo, Host
::GetSignalAsCString(signo), GetID()); } while (0)
1152 Host::GetSignalAsCString(signo), GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "sending signal {0} ({1}) to pid {1}", signo, Host
::GetSignalAsCString(signo), GetID()); } while (0)
;
1153
1154 if (kill(GetID(), signo))
1155 error.SetErrorToErrno();
1156
1157 return error;
1158}
1159
1160Status NativeProcessLinux::Interrupt() {
1161 // Pick a running thread (or if none, a not-dead stopped thread) as the
1162 // chosen thread that will be the stop-reason thread.
1163 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1164
1165 NativeThreadProtocol *running_thread = nullptr;
1166 NativeThreadProtocol *stopped_thread = nullptr;
1167
1168 LLDB_LOG(log, "selecting running thread for interrupt target")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "selecting running thread for interrupt target");
} while (0)
;
1169 for (const auto &thread : m_threads) {
1170 // If we have a running or stepping thread, we'll call that the target of
1171 // the interrupt.
1172 const auto thread_state = thread->GetState();
1173 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1174 running_thread = thread.get();
1175 break;
1176 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1177 // Remember the first non-dead stopped thread. We'll use that as a
1178 // backup if there are no running threads.
1179 stopped_thread = thread.get();
1180 }
1181 }
1182
1183 if (!running_thread && !stopped_thread) {
1184 Status error("found no running/stepping or live stopped threads as target "
1185 "for interrupt");
1186 LLDB_LOG(log, "skipping due to error: {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "skipping due to error: {0}", error); } while (0)
;
1187
1188 return error;
1189 }
1190
1191 NativeThreadProtocol *deferred_signal_thread =
1192 running_thread ? running_thread : stopped_thread;
1193
1194 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
1195 running_thread ? "running" : "stopped",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
1196 deferred_signal_thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
;
1197
1198 StopRunningThreads(deferred_signal_thread->GetID());
1199
1200 return Status();
1201}
1202
1203Status NativeProcessLinux::Kill() {
1204 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1205 LLDB_LOG(log, "pid {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0}", GetID()); } while (0)
;
1206
1207 Status error;
1208
1209 switch (m_state) {
1210 case StateType::eStateInvalid:
1211 case StateType::eStateExited:
1212 case StateType::eStateCrashed:
1213 case StateType::eStateDetached:
1214 case StateType::eStateUnloaded:
1215 // Nothing to do - the process is already dead.
1216 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ignored for PID {0} due to current state: {1}", GetID
(), m_state); } while (0)
1217 m_state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ignored for PID {0} due to current state: {1}", GetID
(), m_state); } while (0)
;
1218 return error;
1219
1220 case StateType::eStateConnected:
1221 case StateType::eStateAttaching:
1222 case StateType::eStateLaunching:
1223 case StateType::eStateStopped:
1224 case StateType::eStateRunning:
1225 case StateType::eStateStepping:
1226 case StateType::eStateSuspended:
1227 // We can try to kill a process in these states.
1228 break;
1229 }
1230
1231 if (kill(GetID(), SIGKILL9) != 0) {
1232 error.SetErrorToErrno();
1233 return error;
1234 }
1235
1236 return error;
1237}
1238
1239static Status
1240ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1241 MemoryRegionInfo &memory_region_info) {
1242 memory_region_info.Clear();
1243
1244 StringExtractor line_extractor(maps_line);
1245
1246 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1247 // pathname perms: rwxp (letter is present if set, '-' if not, final
1248 // character is p=private, s=shared).
1249
1250 // Parse out the starting address
1251 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1252
1253 // Parse out hyphen separating start and end address from range.
1254 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1255 return Status(
1256 "malformed /proc/{pid}/maps entry, missing dash between address range");
1257
1258 // Parse out the ending address
1259 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1260
1261 // Parse out the space after the address.
1262 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1263 return Status(
1264 "malformed /proc/{pid}/maps entry, missing space after range");
1265
1266 // Save the range.
1267 memory_region_info.GetRange().SetRangeBase(start_address);
1268 memory_region_info.GetRange().SetRangeEnd(end_address);
1269
1270 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1271 // process.
1272 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1273
1274 // Parse out each permission entry.
1275 if (line_extractor.GetBytesLeft() < 4)
1276 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1277 "permissions");
1278
1279 // Handle read permission.
1280 const char read_perm_char = line_extractor.GetChar();
1281 if (read_perm_char == 'r')
1282 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1283 else if (read_perm_char == '-')
1284 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1285 else
1286 return Status("unexpected /proc/{pid}/maps read permission char");
1287
1288 // Handle write permission.
1289 const char write_perm_char = line_extractor.GetChar();
1290 if (write_perm_char == 'w')
1291 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1292 else if (write_perm_char == '-')
1293 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1294 else
1295 return Status("unexpected /proc/{pid}/maps write permission char");
1296
1297 // Handle execute permission.
1298 const char exec_perm_char = line_extractor.GetChar();
1299 if (exec_perm_char == 'x')
1300 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1301 else if (exec_perm_char == '-')
1302 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1303 else
1304 return Status("unexpected /proc/{pid}/maps exec permission char");
1305
1306 line_extractor.GetChar(); // Read the private bit
1307 line_extractor.SkipSpaces(); // Skip the separator
1308 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1309 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1310 line_extractor.GetChar(); // Read the device id separator
1311 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1312 line_extractor.SkipSpaces(); // Skip the separator
1313 line_extractor.GetU64(0, 10); // Read the inode number
1314
1315 line_extractor.SkipSpaces();
1316 const char *name = line_extractor.Peek();
1317 if (name)
1318 memory_region_info.SetName(name);
1319
1320 return Status();
1321}
1322
1323Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1324 MemoryRegionInfo &range_info) {
1325 // FIXME review that the final memory region returned extends to the end of
1326 // the virtual address space,
1327 // with no perms if it is not mapped.
1328
1329 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1330 // proc maps entries are in ascending order.
1331 // FIXME assert if we find differently.
1332
1333 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1334 // We're done.
1335 return Status("unsupported");
1336 }
1337
1338 Status error = PopulateMemoryRegionCache();
1339 if (error.Fail()) {
1340 return error;
1341 }
1342
1343 lldb::addr_t prev_base_address = 0;
1344
1345 // FIXME start by finding the last region that is <= target address using
1346 // binary search. Data is sorted.
1347 // There can be a ton of regions on pthreads apps with lots of threads.
1348 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1349 ++it) {
1350 MemoryRegionInfo &proc_entry_info = it->first;
1351
1352 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1353 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&(((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address
) && "descending /proc/pid/maps entries detected, unexpected"
) ? static_cast<void> (0) : __assert_fail ("(proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && \"descending /proc/pid/maps entries detected, unexpected\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1354, __PRETTY_FUNCTION__))
1354 "descending /proc/pid/maps entries detected, unexpected")(((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address
) && "descending /proc/pid/maps entries detected, unexpected"
) ? static_cast<void> (0) : __assert_fail ("(proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && \"descending /proc/pid/maps entries detected, unexpected\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1354, __PRETTY_FUNCTION__))
;
1355 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1356 UNUSED_IF_ASSERT_DISABLED(prev_base_address)((void)(prev_base_address));
1357
1358 // If the target address comes before this entry, indicate distance to next
1359 // region.
1360 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1361 range_info.GetRange().SetRangeBase(load_addr);
1362 range_info.GetRange().SetByteSize(
1363 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1364 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1365 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1366 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1367 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1368
1369 return error;
1370 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1371 // The target address is within the memory region we're processing here.
1372 range_info = proc_entry_info;
1373 return error;
1374 }
1375
1376 // The target memory address comes somewhere after the region we just
1377 // parsed.
1378 }
1379
1380 // If we made it here, we didn't find an entry that contained the given
1381 // address. Return the load_addr as start and the amount of bytes betwwen
1382 // load address and the end of the memory as size.
1383 range_info.GetRange().SetRangeBase(load_addr);
1384 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1385 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1386 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1387 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1388 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1389 return error;
1390}
1391
1392Status NativeProcessLinux::PopulateMemoryRegionCache() {
1393 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1394
1395 // If our cache is empty, pull the latest. There should always be at least
1396 // one memory region if memory region handling is supported.
1397 if (!m_mem_region_cache.empty()) {
1398 LLDB_LOG(log, "reusing {0} cached memory region entries",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "reusing {0} cached memory region entries", m_mem_region_cache
.size()); } while (0)
1399 m_mem_region_cache.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "reusing {0} cached memory region entries", m_mem_region_cache
.size()); } while (0)
;
1400 return Status();
1401 }
1402
1403 auto BufferOrError = getProcFile(GetID(), "maps");
1404 if (!BufferOrError) {
1405 m_supports_mem_region = LazyBool::eLazyBoolNo;
1406 return BufferOrError.getError();
1407 }
1408 StringRef Rest = BufferOrError.get()->getBuffer();
1409 while (! Rest.empty()) {
1410 StringRef Line;
1411 std::tie(Line, Rest) = Rest.split('\n');
1412 MemoryRegionInfo info;
1413 const Status parse_error =
1414 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
1415 if (parse_error.Fail()) {
1416 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to parse proc maps line '{0}': {1}", Line
, parse_error); } while (0)
1417 parse_error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to parse proc maps line '{0}': {1}", Line
, parse_error); } while (0)
;
1418 m_supports_mem_region = LazyBool::eLazyBoolNo;
1419 return parse_error;
1420 }
1421 m_mem_region_cache.emplace_back(
1422 info, FileSpec(info.GetName().GetCString(), true));
1423 }
1424
1425 if (m_mem_region_cache.empty()) {
1426 // No entries after attempting to read them. This shouldn't happen if
1427 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1428 // procfs.
1429 m_supports_mem_region = LazyBool::eLazyBoolNo;
1430 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
1431 "failed to find any procfs maps entries, assuming no support "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
1432 "for memory region metadata retrieval")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
;
1433 return Status("not supported");
1434 }
1435
1436 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "read {0} memory region entries from /proc/{1}/maps"
, m_mem_region_cache.size(), GetID()); } while (0)
1437 m_mem_region_cache.size(), GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "read {0} memory region entries from /proc/{1}/maps"
, m_mem_region_cache.size(), GetID()); } while (0)
;
1438
1439 // We support memory retrieval, remember that.
1440 m_supports_mem_region = LazyBool::eLazyBoolYes;
1441 return Status();
1442}
1443
1444void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1445 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1446 LLDB_LOG(log, "newBumpId={0}", newBumpId)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "newBumpId={0}", newBumpId); } while (0)
;
1447 LLDB_LOG(log, "clearing {0} entries from memory region cache",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "clearing {0} entries from memory region cache", m_mem_region_cache
.size()); } while (0)
1448 m_mem_region_cache.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "clearing {0} entries from memory region cache", m_mem_region_cache
.size()); } while (0)
;
1449 m_mem_region_cache.clear();
1450}
1451
1452Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1453 lldb::addr_t &addr) {
1454// FIXME implementing this requires the equivalent of
1455// InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1456// working with Native*Protocol.
1457#if 1
1458 return Status("not implemented yet");
1459#else
1460 addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1461
1462 unsigned prot = 0;
1463 if (permissions & lldb::ePermissionsReadable)
1464 prot |= eMmapProtRead;
1465 if (permissions & lldb::ePermissionsWritable)
1466 prot |= eMmapProtWrite;
1467 if (permissions & lldb::ePermissionsExecutable)
1468 prot |= eMmapProtExec;
1469
1470 // TODO implement this directly in NativeProcessLinux
1471 // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1472 if (InferiorCallMmap(this, addr, 0, size, prot,
1473 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1474 m_addr_to_mmap_size[addr] = size;
1475 return Status();
1476 } else {
1477 addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1478 return Status("unable to allocate %" PRIu64"l" "u"
1479 " bytes of memory with permissions %s",
1480 size, GetPermissionsAsCString(permissions));
1481 }
1482#endif
1483}
1484
1485Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1486 // FIXME see comments in AllocateMemory - required lower-level
1487 // bits not in place yet (ThreadPlans)
1488 return Status("not implemented");
1489}
1490
1491lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1492 // punt on this for now
1493 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
1494}
1495
1496size_t NativeProcessLinux::UpdateThreads() {
1497 // The NativeProcessLinux monitoring threads are always up to date with
1498 // respect to thread state and they keep the thread list populated properly.
1499 // All this method needs to do is return the thread count.
1500 return m_threads.size();
1501}
1502
1503Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1504 bool hardware) {
1505 if (hardware)
1506 return SetHardwareBreakpoint(addr, size);
1507 else
1508 return SetSoftwareBreakpoint(addr, size);
1509}
1510
1511Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1512 if (hardware)
1513 return RemoveHardwareBreakpoint(addr);
1514 else
1515 return NativeProcessProtocol::RemoveBreakpoint(addr);
1516}
1517
1518llvm::Expected<llvm::ArrayRef<uint8_t>>
1519NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1520 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1521 // linux kernel does otherwise.
1522 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1523 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1524
1525 switch (GetArchitecture().GetMachine()) {
1526 case llvm::Triple::arm:
1527 switch (size_hint) {
1528 case 2:
1529 return llvm::makeArrayRef(g_thumb_opcode);
1530 case 4:
1531 return llvm::makeArrayRef(g_arm_opcode);
1532 default:
1533 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1534 "Unrecognised trap opcode size hint!");
1535 }
1536 default:
1537 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1538 }
1539}
1540
1541Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1542 size_t &bytes_read) {
1543 if (ProcessVmReadvSupported()) {
1544 // The process_vm_readv path is about 50 times faster than ptrace api. We
1545 // want to use this syscall if it is supported.
1546
1547 const ::pid_t pid = GetID();
1548
1549 struct iovec local_iov, remote_iov;
1550 local_iov.iov_base = buf;
1551 local_iov.iov_len = size;
1552 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1553 remote_iov.iov_len = size;
1554
1555 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1556 const bool success = bytes_read == size;
1557
1558 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1559 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1560 "using process_vm_readv to read {0} bytes from inferior "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1561 "address {1:x}: {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1562 size, addr, success ? "Success" : llvm::sys::StrError(errno))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
;
1563
1564 if (success)
1565 return Status();
1566 // else the call failed for some reason, let's retry the read using ptrace
1567 // api.
1568 }
1569
1570 unsigned char *dst = static_cast<unsigned char *>(buf);
1571 size_t remainder;
1572 long data;
1573
1574 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY(1u << 4)));
1575 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "addr = {0}, buf = {1}, size = {2}", addr, buf, size
); } while (0)
;
1576
1577 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1578 Status error = NativeProcessLinux::PtraceWrapper(
1579 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1580 if (error.Fail())
1581 return error;
1582
1583 remainder = size - bytes_read;
1584 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1585
1586 // Copy the data into our buffer
1587 memcpy(dst, &data, remainder);
1588
1589 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x}", addr, data); } while (0)
;
1590 addr += k_ptrace_word_size;
1591 dst += k_ptrace_word_size;
1592 }
1593 return Status();
1594}
1595
1596Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1597 size_t size, size_t &bytes_written) {
1598 const unsigned char *src = static_cast<const unsigned char *>(buf);
1599 size_t remainder;
1600 Status error;
1601
1602 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY(1u << 4)));
1603 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "addr = {0}, buf = {1}, size = {2}", addr, buf, size
); } while (0)
;
1604
1605 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1606 remainder = size - bytes_written;
1607 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1608
1609 if (remainder == k_ptrace_word_size) {
1610 unsigned long data = 0;
1611 memcpy(&data, src, k_ptrace_word_size);
1612
1613 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x}", addr, data); } while (0)
;
1614 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1615 (void *)addr, (void *)data);
1616 if (error.Fail())
1617 return error;
1618 } else {
1619 unsigned char buff[8];
1620 size_t bytes_read;
1621 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1622 if (error.Fail())
1623 return error;
1624
1625 memcpy(buff, src, remainder);
1626
1627 size_t bytes_written_rec;
1628 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1629 if (error.Fail())
1630 return error;
1631
1632 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long
*)src, *(unsigned long *)buff); } while (0)
1633 *(unsigned long *)buff)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long
*)src, *(unsigned long *)buff); } while (0)
;
1634 }
1635
1636 addr += k_ptrace_word_size;
1637 src += k_ptrace_word_size;
1638 }
1639 return error;
1640}
1641
1642Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
1643 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1644}
1645
1646Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1647 unsigned long *message) {
1648 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1649}
1650
1651Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1652 if (tid == LLDB_INVALID_THREAD_ID0)
1653 return Status();
1654
1655 return PtraceWrapper(PTRACE_DETACH, tid);
1656}
1657
1658bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1659 for (const auto &thread : m_threads) {
1660 assert(thread && "thread list should not contain NULL threads")((thread && "thread list should not contain NULL threads"
) ? static_cast<void> (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1660, __PRETTY_FUNCTION__))
;
1661 if (thread->GetID() == thread_id) {
1662 // We have this thread.
1663 return true;
1664 }
1665 }
1666
1667 // We don't have this thread.
1668 return false;
1669}
1670
1671bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1672 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD(1u << 2));
1673 LLDB_LOG(log, "tid: {0})", thread_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0})", thread_id); } while (0)
;
1674
1675 bool found = false;
1676 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1677 if (*it && ((*it)->GetID() == thread_id)) {
1678 m_threads.erase(it);
1679 found = true;
1680 break;
1681 }
1682 }
1683
1684 if (found)
1685 StopTracingForThread(thread_id);
1686 SignalIfAllThreadsStopped();
1687 return found;
1688}
1689
1690NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1691 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD(1u << 2)));
1692 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} adding thread with tid {1}", GetID(), thread_id
); } while (0)
;
1693
1694 assert(!HasThreadNoLock(thread_id) &&((!HasThreadNoLock(thread_id) && "attempted to add a thread by id that already exists"
) ? static_cast<void> (0) : __assert_fail ("!HasThreadNoLock(thread_id) && \"attempted to add a thread by id that already exists\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1695, __PRETTY_FUNCTION__))
1695 "attempted to add a thread by id that already exists")((!HasThreadNoLock(thread_id) && "attempted to add a thread by id that already exists"
) ? static_cast<void> (0) : __assert_fail ("!HasThreadNoLock(thread_id) && \"attempted to add a thread by id that already exists\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1695, __PRETTY_FUNCTION__))
;
1696
1697 // If this is the first thread, save it as the current thread
1698 if (m_threads.empty())
1699 SetCurrentThreadID(thread_id);
1700
1701 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
1702
1703 if (m_pt_proces_trace_id != LLDB_INVALID_UID(18446744073709551615UL)) {
1704 auto traceMonitor = ProcessorTraceMonitor::Create(
1705 GetID(), thread_id, m_pt_process_trace_config, true);
1706 if (traceMonitor) {
1707 m_pt_traced_thread_group.insert(thread_id);
1708 m_processor_trace_monitor.insert(
1709 std::make_pair(thread_id, std::move(*traceMonitor)));
1710 } else {
1711 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to start trace on thread {0}", thread_id)
; } while (0)
;
1712 Status error(traceMonitor.takeError());
1713 LLDB_LOG(log, "error {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "error {0}", error); } while (0)
;
1714 }
1715 }
1716
1717 return static_cast<NativeThreadLinux &>(*m_threads.back());
1718}
1719
1720Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1721 FileSpec &file_spec) {
1722 Status error = PopulateMemoryRegionCache();
1723 if (error.Fail())
1724 return error;
1725
1726 FileSpec module_file_spec(module_path, true);
1727
1728 file_spec.Clear();
1729 for (const auto &it : m_mem_region_cache) {
1730 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1731 file_spec = it.second;
1732 return Status();
1733 }
1734 }
1735 return Status("Module file (%s) not found in /proc/%" PRIu64"l" "u" "/maps file!",
1736 module_file_spec.GetFilename().AsCString(), GetID());
1737}
1738
1739Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1740 lldb::addr_t &load_addr) {
1741 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1742 Status error = PopulateMemoryRegionCache();
1743 if (error.Fail())
1744 return error;
1745
1746 FileSpec file(file_name, false);
1747 for (const auto &it : m_mem_region_cache) {
1748 if (it.second == file) {
1749 load_addr = it.first.GetRange().GetRangeBase();
1750 return Status();
1751 }
1752 }
1753 return Status("No load address found for specified file.");
1754}
1755
1756NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1757 return static_cast<NativeThreadLinux *>(
1758 NativeProcessProtocol::GetThreadByID(tid));
1759}
1760
1761Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1762 lldb::StateType state, int signo) {
1763 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD(1u << 2));
1764 LLDB_LOG(log, "tid: {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0}", thread.GetID()); } while (0)
;
1765
1766 // Before we do the resume below, first check if we have a pending stop
1767 // notification that is currently waiting for all threads to stop. This is
1768 // potentially a buggy situation since we're ostensibly waiting for threads
1769 // to stop before we send out the pending notification, and here we are
1770 // resuming one before we send out the pending stop notification.
1771 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0) {
1772 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1773 "about to resume tid {0} per explicit request but we have a "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1774 "pending stop notification (tid {1}) that is actively "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1775 "waiting for this thread to stop. Valid sequence of events?",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1776 thread.GetID(), m_pending_notification_tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
;
1777 }
1778
1779 // Request a resume. We expect this to be synchronous and the system to
1780 // reflect it is running after this completes.
1781 switch (state) {
1782 case eStateRunning: {
1783 const auto resume_result = thread.Resume(signo);
1784 if (resume_result.Success())
1785 SetState(eStateRunning, true);
1786 return resume_result;
1787 }
1788 case eStateStepping: {
1789 const auto step_result = thread.SingleStep(signo);
1790 if (step_result.Success())
1791 SetState(eStateRunning, true);
1792 return step_result;
1793 }
1794 default:
1795 LLDB_LOG(log, "Unhandled state {0}.", state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Unhandled state {0}.", state); } while (0)
;
1796 llvm_unreachable("Unhandled state for resume")::llvm::llvm_unreachable_internal("Unhandled state for resume"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1796)
;
1797 }
1798}
1799
1800//===----------------------------------------------------------------------===//
1801
1802void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1803 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD(1u << 2));
1804 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to process event: (triggering_tid: {0})", triggering_tid
); } while (0)
1805 triggering_tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to process event: (triggering_tid: {0})", triggering_tid
); } while (0)
;
1806
1807 m_pending_notification_tid = triggering_tid;
1808
1809 // Request a stop for all the thread stops that need to be stopped and are
1810 // not already known to be stopped.
1811 for (const auto &thread : m_threads) {
1812 if (StateIsRunningState(thread->GetState()))
1813 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1814 }
1815
1816 SignalIfAllThreadsStopped();
1817 LLDB_LOG(log, "event processing done")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "event processing done"); } while (0)
;
1818}
1819
1820void NativeProcessLinux::SignalIfAllThreadsStopped() {
1821 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID0)
1822 return; // No pending notification. Nothing to do.
1823
1824 for (const auto &thread_sp : m_threads) {
1825 if (StateIsRunningState(thread_sp->GetState()))
1826 return; // Some threads are still running. Don't signal yet.
1827 }
1828
1829 // We have a pending notification and all threads have stopped.
1830 Log *log(
1831 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1) | LIBLLDB_LOG_BREAKPOINTS(1u << 5)));
1832
1833 // Clear any temporary breakpoints we used to implement software single
1834 // stepping.
1835 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1836 Status error = RemoveBreakpoint(thread_info.second);
1837 if (error.Fail())
1838 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0} remove stepping breakpoint: {1}", thread_info
.first, error); } while (0)
1839 thread_info.first, error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0} remove stepping breakpoint: {1}", thread_info
.first, error); } while (0)
;
1840 }
1841 m_threads_stepping_with_breakpoint.clear();
1842
1843 // Notify the delegate about the stop
1844 SetCurrentThreadID(m_pending_notification_tid);
1845 SetState(StateType::eStateStopped, true);
1846 m_pending_notification_tid = LLDB_INVALID_THREAD_ID0;
1847}
1848
1849void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1850 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD(1u << 2));
1851 LLDB_LOG(log, "tid: {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0}", thread.GetID()); } while (0)
;
1852
1853 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0 &&
1854 StateIsRunningState(thread.GetState())) {
1855 // We will need to wait for this new thread to stop as well before firing
1856 // the notification.
1857 thread.RequestStop();
1858 }
1859}
1860
1861void NativeProcessLinux::SigchldHandler() {
1862 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS(1u << 1)));
1863 // Process all pending waitpid notifications.
1864 while (true) {
1865 int status = -1;
1866 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1867 __WALL0x40000000 | __WNOTHREAD0x20000000 | WNOHANG1);
1868
1869 if (wait_pid == 0)
1870 break; // We are done.
1871
1872 if (wait_pid == -1) {
1873 Status error(errno(*__errno_location ()), eErrorTypePOSIX);
1874 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid (-1, &status, _) failed: {0}", error
); } while (0)
;
1875 break;
1876 }
1877
1878 WaitStatus wait_status = WaitStatus::Decode(status);
1879 bool exited = wait_status.type == WaitStatus::Exit ||
1880 (wait_status.type == WaitStatus::Signal &&
1881 wait_pid == static_cast<::pid_t>(GetID()));
1882
1883 LLDB_LOG(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}"
, wait_pid, wait_status, exited); } while (0)
1884 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}"
, wait_pid, wait_status, exited); } while (0)
1885 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}"
, wait_pid, wait_status, exited); } while (0)
1886 wait_pid, wait_status, exited)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}"
, wait_pid, wait_status, exited); } while (0)
;
1887
1888 MonitorCallback(wait_pid, exited, wait_status);
1889 }
1890}
1891
1892// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1893// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1894Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1895 void *data, size_t data_size,
1896 long *result) {
1897 Status error;
1898 long int ret;
1899
1900 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
1901
1902 PtraceDisplayBytes(req, data, data_size);
1903
1904 errno(*__errno_location ()) = 0;
1905 if (req == PTRACE_GETREGSETPTRACE_GETREGSET || req == PTRACE_SETREGSETPTRACE_SETREGSET)
1906 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1907 *(unsigned int *)addr, data);
1908 else
1909 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1910 addr, data);
1911
1912 if (ret == -1)
1913 error.SetErrorToErrno();
1914
1915 if (result)
1916 *result = ret;
1917
1918 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid
, addr, data, data_size, ret); } while (0)
1919 data_size, ret)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid
, addr, data, data_size, ret); } while (0)
;
1920
1921 PtraceDisplayBytes(req, data, data_size);
1922
1923 if (error.Fail())
1924 LLDB_LOG(log, "ptrace() failed: {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace() failed: {0}", error); } while (0)
;
1925
1926 return error;
1927}
1928
1929llvm::Expected<ProcessorTraceMonitor &>
1930NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
1931 lldb::tid_t thread) {
1932 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
1933 if (thread == LLDB_INVALID_THREAD_ID0 && traceid == m_pt_proces_trace_id) {
1934 LLDB_LOG(log, "thread not specified: {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "thread not specified: {0}", traceid); } while (0
)
;
1935 return Status("tracing not active thread not specified").ToError();
1936 }
1937
1938 for (auto& iter : m_processor_trace_monitor) {
1939 if (traceid == iter.second->GetTraceID() &&
1940 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID0))
1941 return *(iter.second);
1942 }
1943
1944 LLDB_LOG(log, "traceid not being traced: {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid not being traced: {0}", traceid); } while
(0)
;
1945 return Status("tracing not active for this thread").ToError();
1946}
1947
1948Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
1949 lldb::tid_t thread,
1950 llvm::MutableArrayRef<uint8_t> &buffer,
1951 size_t offset) {
1952 TraceOptions trace_options;
1953 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
1954 Status error;
1955
1956 LLDB_LOG(log, "traceid {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid {0}", traceid); } while (0)
;
1957
1958 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1959 if (!perf_monitor) {
1960 LLDB_LOG(log, "traceid not being traced: {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid not being traced: {0}", traceid); } while
(0)
;
1961 buffer = buffer.slice(buffer.size());
1962 error = perf_monitor.takeError();
1963 return error;
1964 }
1965 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
1966}
1967
1968Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
1969 llvm::MutableArrayRef<uint8_t> &buffer,
1970 size_t offset) {
1971 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
1972 Status error;
1973
1974 LLDB_LOG(log, "traceid {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid {0}", traceid); } while (0)
;
1975
1976 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1977 if (!perf_monitor) {
1978 LLDB_LOG(log, "traceid not being traced: {0}", traceid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid not being traced: {0}", traceid); } while
(0)
;
1979 buffer = buffer.slice(buffer.size());
1980 error = perf_monitor.takeError();
1981 return error;
1982 }
1983 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
1984}
1985
1986Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
1987 TraceOptions &config) {
1988 Status error;
1989 if (config.getThreadID() == LLDB_INVALID_THREAD_ID0 &&
1990 m_pt_proces_trace_id == traceid) {
1991 if (m_pt_proces_trace_id == LLDB_INVALID_UID(18446744073709551615UL)) {
1992 error.SetErrorString("tracing not active for this process");
1993 return error;
1994 }
1995 config = m_pt_process_trace_config;
1996 } else {
1997 auto perf_monitor =
1998 LookupProcessorTraceInstance(traceid, config.getThreadID());
1999 if (!perf_monitor) {
2000 error = perf_monitor.takeError();
2001 return error;
2002 }
2003 error = (*perf_monitor).GetTraceConfig(config);
2004 }
2005 return error;
2006}
2007
2008lldb::user_id_t
2009NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2010 Status &error) {
2011
2012 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
2013 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2014 return LLDB_INVALID_UID(18446744073709551615UL);
2015
2016 if (m_pt_proces_trace_id != LLDB_INVALID_UID(18446744073709551615UL)) {
2017 error.SetErrorString("tracing already active on this process");
2018 return m_pt_proces_trace_id;
2019 }
2020
2021 for (const auto &thread_sp : m_threads) {
2022 if (auto traceInstance = ProcessorTraceMonitor::Create(
2023 GetID(), thread_sp->GetID(), config, true)) {
2024 m_pt_traced_thread_group.insert(thread_sp->GetID());
2025 m_processor_trace_monitor.insert(
2026 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2027 }
2028 }
2029
2030 m_pt_process_trace_config = config;
2031 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2032
2033 // Trace on Complete process will have traceid of 0
2034 m_pt_proces_trace_id = 0;
2035
2036 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Process Trace ID {0}", m_pt_proces_trace_id); } while
(0)
;
2037 return m_pt_proces_trace_id;
2038}
2039
2040lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2041 Status &error) {
2042 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2043 return NativeProcessProtocol::StartTrace(config, error);
2044
2045 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
2046
2047 lldb::tid_t threadid = config.getThreadID();
2048
2049 if (threadid == LLDB_INVALID_THREAD_ID0)
2050 return StartTraceGroup(config, error);
2051
2052 auto thread_sp = GetThreadByID(threadid);
2053 if (!thread_sp) {
2054 // Thread not tracked by lldb so don't trace.
2055 error.SetErrorString("invalid thread id");
2056 return LLDB_INVALID_UID(18446744073709551615UL);
2057 }
2058
2059 const auto &iter = m_processor_trace_monitor.find(threadid);
2060 if (iter != m_processor_trace_monitor.end()) {
2061 LLDB_LOG(log, "Thread already being traced")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Thread already being traced"); } while (0)
;
2062 error.SetErrorString("tracing already active on this thread");
2063 return LLDB_INVALID_UID(18446744073709551615UL);
2064 }
2065
2066 auto traceMonitor =
2067 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2068 if (!traceMonitor) {
2069 error = traceMonitor.takeError();
2070 LLDB_LOG(log, "error {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "error {0}", error); } while (0)
;
2071 return LLDB_INVALID_UID(18446744073709551615UL);
2072 }
2073 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2074 m_processor_trace_monitor.insert(
2075 std::make_pair(threadid, std::move(*traceMonitor)));
2076 return ret_trace_id;
2077}
2078
2079Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2080 Status error;
2081 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
2082 LLDB_LOG(log, "Thread {0}", thread)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Thread {0}", thread); } while (0)
;
2083
2084 const auto& iter = m_processor_trace_monitor.find(thread);
2085 if (iter == m_processor_trace_monitor.end()) {
2086 error.SetErrorString("tracing not active for this thread");
2087 return error;
2088 }
2089
2090 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2091 // traceid maps to the whole process so we have to erase it from the thread
2092 // group.
2093 LLDB_LOG(log, "traceid maps to process")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid maps to process"); } while (0)
;
2094 m_pt_traced_thread_group.erase(thread);
2095 }
2096 m_processor_trace_monitor.erase(iter);
2097
2098 return error;
2099}
2100
2101Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2102 lldb::tid_t thread) {
2103 Status error;
2104
2105 TraceOptions trace_options;
2106 trace_options.setThreadID(thread);
2107 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2108
2109 if (error.Fail())
2110 return error;
2111
2112 switch (trace_options.getType()) {
2113 case lldb::TraceType::eTraceTypeProcessorTrace:
2114 if (traceid == m_pt_proces_trace_id &&
2115 thread == LLDB_INVALID_THREAD_ID0)
2116 StopProcessorTracingOnProcess();
2117 else
2118 error = StopProcessorTracingOnThread(traceid, thread);
2119 break;
2120 default:
2121 error.SetErrorString("trace not supported");
2122 break;
2123 }
2124
2125 return error;
2126}
2127
2128void NativeProcessLinux::StopProcessorTracingOnProcess() {
2129 for (auto thread_id_iter : m_pt_traced_thread_group)
2130 m_processor_trace_monitor.erase(thread_id_iter);
2131 m_pt_traced_thread_group.clear();
2132 m_pt_proces_trace_id = LLDB_INVALID_UID(18446744073709551615UL);
2133}
2134
2135Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2136 lldb::tid_t thread) {
2137 Status error;
2138 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE(1u << 5)));
2139
2140 if (thread == LLDB_INVALID_THREAD_ID0) {
2141 for (auto& iter : m_processor_trace_monitor) {
2142 if (iter.second->GetTraceID() == traceid) {
2143 // Stopping a trace instance for an individual thread hence there will
2144 // only be one traceid that can match.
2145 m_processor_trace_monitor.erase(iter.first);
2146 return error;
2147 }
2148 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Trace ID {0}", iter.second->GetTraceID()); } while
(0)
;
2149 }
2150
2151 LLDB_LOG(log, "Invalid TraceID")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Invalid TraceID"); } while (0)
;
2152 error.SetErrorString("invalid trace id");
2153 return error;
2154 }
2155
2156 // thread is specified so we can use find function on the map.
2157 const auto& iter = m_processor_trace_monitor.find(thread);
2158 if (iter == m_processor_trace_monitor.end()) {
2159 // thread not found in our map.
2160 LLDB_LOG(log, "thread not being traced")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "thread not being traced"); } while (0)
;
2161 error.SetErrorString("tracing not active for this thread");
2162 return error;
2163 }
2164 if (iter->second->GetTraceID() != traceid) {
2165 // traceid did not match so it has to be invalid.
2166 LLDB_LOG(log, "Invalid TraceID")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Invalid TraceID"); } while (0)
;
2167 error.SetErrorString("invalid trace id");
2168 return error;
2169 }
2170
2171 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "UID - {0} , Thread -{1}", traceid, thread); } while
(0)
;
2172
2173 if (traceid == m_pt_proces_trace_id) {
2174 // traceid maps to the whole process so we have to erase it from the thread
2175 // group.
2176 LLDB_LOG(log, "traceid maps to process")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "traceid maps to process"); } while (0)
;
2177 m_pt_traced_thread_group.erase(thread);
2178 }
2179 m_processor_trace_monitor.erase(iter);
2180
2181 return error;
2182}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- 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// This file defines an API used to report recoverable errors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_ERROR_H
15#define LLVM_SUPPORT_ERROR_H
16
17#include "llvm-c/Error.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Config/abi-breaking.h"
23#include "llvm/Support/AlignOf.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/ErrorOr.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31#include <cassert>
32#include <cstdint>
33#include <cstdlib>
34#include <functional>
35#include <memory>
36#include <new>
37#include <string>
38#include <system_error>
39#include <type_traits>
40#include <utility>
41#include <vector>
42
43namespace llvm {
44
45class ErrorSuccess;
46
47/// Base class for error info classes. Do not extend this directly: Extend
48/// the ErrorInfo template subclass instead.
49class ErrorInfoBase {
50public:
51 virtual ~ErrorInfoBase() = default;
52
53 /// Print an error message to an output stream.
54 virtual void log(raw_ostream &OS) const = 0;
55
56 /// Return the error message as a string.
57 virtual std::string message() const {
58 std::string Msg;
59 raw_string_ostream OS(Msg);
60 log(OS);
61 return OS.str();
62 }
63
64 /// Convert this error to a std::error_code.
65 ///
66 /// This is a temporary crutch to enable interaction with code still
67 /// using std::error_code. It will be removed in the future.
68 virtual std::error_code convertToErrorCode() const = 0;
69
70 // Returns the class ID for this type.
71 static const void *classID() { return &ID; }
72
73 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
74 virtual const void *dynamicClassID() const = 0;
75
76 // Check whether this instance is a subclass of the class identified by
77 // ClassID.
78 virtual bool isA(const void *const ClassID) const {
79 return ClassID == classID();
80 }
81
82 // Check whether this instance is a subclass of ErrorInfoT.
83 template <typename ErrorInfoT> bool isA() const {
84 return isA(ErrorInfoT::classID());
85 }
86
87private:
88 virtual void anchor();
89
90 static char ID;
91};
92
93/// Lightweight error class with error context and mandatory checking.
94///
95/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
96/// are represented by setting the pointer to a ErrorInfoBase subclass
97/// instance containing information describing the failure. Success is
98/// represented by a null pointer value.
99///
100/// Instances of Error also contains a 'Checked' flag, which must be set
101/// before the destructor is called, otherwise the destructor will trigger a
102/// runtime error. This enforces at runtime the requirement that all Error
103/// instances be checked or returned to the caller.
104///
105/// There are two ways to set the checked flag, depending on what state the
106/// Error instance is in. For Error instances indicating success, it
107/// is sufficient to invoke the boolean conversion operator. E.g.:
108///
109/// @code{.cpp}
110/// Error foo(<...>);
111///
112/// if (auto E = foo(<...>))
113/// return E; // <- Return E if it is in the error state.
114/// // We have verified that E was in the success state. It can now be safely
115/// // destroyed.
116/// @endcode
117///
118/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
119/// without testing the return value will raise a runtime error, even if foo
120/// returns success.
121///
122/// For Error instances representing failure, you must use either the
123/// handleErrors or handleAllErrors function with a typed handler. E.g.:
124///
125/// @code{.cpp}
126/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
127/// // Custom error info.
128/// };
129///
130/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
131///
132/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
133/// auto NewE =
134/// handleErrors(E,
135/// [](const MyErrorInfo &M) {
136/// // Deal with the error.
137/// },
138/// [](std::unique_ptr<OtherError> M) -> Error {
139/// if (canHandle(*M)) {
140/// // handle error.
141/// return Error::success();
142/// }
143/// // Couldn't handle this error instance. Pass it up the stack.
144/// return Error(std::move(M));
145/// );
146/// // Note - we must check or return NewE in case any of the handlers
147/// // returned a new error.
148/// @endcode
149///
150/// The handleAllErrors function is identical to handleErrors, except
151/// that it has a void return type, and requires all errors to be handled and
152/// no new errors be returned. It prevents errors (assuming they can all be
153/// handled) from having to be bubbled all the way to the top-level.
154///
155/// *All* Error instances must be checked before destruction, even if
156/// they're moved-assigned or constructed from Success values that have already
157/// been checked. This enforces checking through all levels of the call stack.
158class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
159 // Both ErrorList and FileError need to be able to yank ErrorInfoBase
160 // pointers out of this class to add to the error list.
161 friend class ErrorList;
162 friend class FileError;
163
164 // handleErrors needs to be able to set the Checked flag.
165 template <typename... HandlerTs>
166 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
167
168 // Expected<T> needs to be able to steal the payload when constructed from an
169 // error.
170 template <typename T> friend class Expected;
171
172 // wrap needs to be able to steal the payload.
173 friend LLVMErrorRef wrap(Error);
174
175protected:
176 /// Create a success value. Prefer using 'Error::success()' for readability
177 Error() {
178 setPtr(nullptr);
179 setChecked(false);
180 }
181
182public:
183 /// Create a success value.
184 static ErrorSuccess success();
185
186 // Errors are not copy-constructable.
187 Error(const Error &Other) = delete;
188
189 /// Move-construct an error value. The newly constructed error is considered
190 /// unchecked, even if the source error had been checked. The original error
191 /// becomes a checked Success value, regardless of its original state.
192 Error(Error &&Other) {
193 setChecked(true);
194 *this = std::move(Other);
195 }
196
197 /// Create an error value. Prefer using the 'make_error' function, but
198 /// this constructor can be useful when "re-throwing" errors from handlers.
199 Error(std::unique_ptr<ErrorInfoBase> Payload) {
200 setPtr(Payload.release());
201 setChecked(false);
8
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'
202 }
203
204 // Errors are not copy-assignable.
205 Error &operator=(const Error &Other) = delete;
206
207 /// Move-assign an error value. The current error must represent success, you
208 /// you cannot overwrite an unhandled error. The current error is then
209 /// considered unchecked. The source error becomes a checked success value,
210 /// regardless of its original state.
211 Error &operator=(Error &&Other) {
212 // Don't allow overwriting of unchecked values.
213 assertIsChecked();
214 setPtr(Other.getPtr());
215
216 // This Error is unchecked, even if the source error was checked.
217 setChecked(false);
218
219 // Null out Other's payload and set its checked bit.
220 Other.setPtr(nullptr);
221 Other.setChecked(true);
222
223 return *this;
224 }
225
226 /// Destroy a Error. Fails with a call to abort() if the error is
227 /// unchecked.
228 ~Error() {
229 assertIsChecked();
230 delete getPtr();
231 }
232
233 /// Bool conversion. Returns true if this Error is in a failure state,
234 /// and false if it is in an accept state. If the error is in a Success state
235 /// it will be considered checked.
236 explicit operator bool() {
237 setChecked(getPtr() == nullptr);
238 return getPtr() != nullptr;
239 }
240
241 /// Check whether one error is a subclass of another.
242 template <typename ErrT> bool isA() const {
243 return getPtr() && getPtr()->isA(ErrT::classID());
244 }
245
246 /// Returns the dynamic class id of this error, or null if this is a success
247 /// value.
248 const void* dynamicClassID() const {
249 if (!getPtr())
250 return nullptr;
251 return getPtr()->dynamicClassID();
252 }
253
254private:
255#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
256 // assertIsChecked() happens very frequently, but under normal circumstances
257 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
258 // of debug prints can cause the function to be too large for inlining. So
259 // it's important that we define this function out of line so that it can't be
260 // inlined.
261 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
262 void fatalUncheckedError() const;
263#endif
264
265 void assertIsChecked() {
266#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
267 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
268 fatalUncheckedError();
269#endif
270 }
271
272 ErrorInfoBase *getPtr() const {
273 return reinterpret_cast<ErrorInfoBase*>(
274 reinterpret_cast<uintptr_t>(Payload) &
275 ~static_cast<uintptr_t>(0x1));
276 }
277
278 void setPtr(ErrorInfoBase *EI) {
279#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
280 Payload = reinterpret_cast<ErrorInfoBase*>(
281 (reinterpret_cast<uintptr_t>(EI) &
282 ~static_cast<uintptr_t>(0x1)) |
283 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
284#else
285 Payload = EI;
286#endif
287 }
288
289 bool getChecked() const {
290#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
291 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
292#else
293 return true;
294#endif
295 }
296
297 void setChecked(bool V) {
298 Payload = reinterpret_cast<ErrorInfoBase*>(
299 (reinterpret_cast<uintptr_t>(Payload) &
300 ~static_cast<uintptr_t>(0x1)) |
301 (V ? 0 : 1));
302 }
303
304 std::unique_ptr<ErrorInfoBase> takePayload() {
305 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
306 setPtr(nullptr);
307 setChecked(true);
308 return Tmp;
309 }
310
311 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
312 if (auto P = E.getPtr())
313 P->log(OS);
314 else
315 OS << "success";
316 return OS;
317 }
318
319 ErrorInfoBase *Payload = nullptr;
320};
321
322/// Subclass of Error for the sole purpose of identifying the success path in
323/// the type system. This allows to catch invalid conversion to Expected<T> at
324/// compile time.
325class ErrorSuccess final : public Error {};
326
327inline ErrorSuccess Error::success() { return ErrorSuccess(); }
328
329/// Make a Error instance representing failure using the given error info
330/// type.
331template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
332 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
4
Calling 'make_unique<llvm::StringError, char const (&)[32], std::error_code>'
6
Returned allocated memory
7
Calling constructor for 'Error'
333}
334
335/// Base class for user error types. Users should declare their error types
336/// like:
337///
338/// class MyError : public ErrorInfo<MyError> {
339/// ....
340/// };
341///
342/// This class provides an implementation of the ErrorInfoBase::kind
343/// method, which is used by the Error RTTI system.
344template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
345class ErrorInfo : public ParentErrT {
346public:
347 using ParentErrT::ParentErrT; // inherit constructors
348
349 static const void *classID() { return &ThisErrT::ID; }
350
351 const void *dynamicClassID() const override { return &ThisErrT::ID; }
352
353 bool isA(const void *const ClassID) const override {
354 return ClassID == classID() || ParentErrT::isA(ClassID);
355 }
356};
357
358/// Special ErrorInfo subclass representing a list of ErrorInfos.
359/// Instances of this class are constructed by joinError.
360class ErrorList final : public ErrorInfo<ErrorList> {
361 // handleErrors needs to be able to iterate the payload list of an
362 // ErrorList.
363 template <typename... HandlerTs>
364 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
365
366 // joinErrors is implemented in terms of join.
367 friend Error joinErrors(Error, Error);
368
369public:
370 void log(raw_ostream &OS) const override {
371 OS << "Multiple errors:\n";
372 for (auto &ErrPayload : Payloads) {
373 ErrPayload->log(OS);
374 OS << "\n";
375 }
376 }
377
378 std::error_code convertToErrorCode() const override;
379
380 // Used by ErrorInfo::classID.
381 static char ID;
382
383private:
384 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
385 std::unique_ptr<ErrorInfoBase> Payload2) {
386 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
387 "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
;
388 Payloads.push_back(std::move(Payload1));
389 Payloads.push_back(std::move(Payload2));
390 }
391
392 static Error join(Error E1, Error E2) {
393 if (!E1)
394 return E2;
395 if (!E2)
396 return E1;
397 if (E1.isA<ErrorList>()) {
398 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
399 if (E2.isA<ErrorList>()) {
400 auto E2Payload = E2.takePayload();
401 auto &E2List = static_cast<ErrorList &>(*E2Payload);
402 for (auto &Payload : E2List.Payloads)
403 E1List.Payloads.push_back(std::move(Payload));
404 } else
405 E1List.Payloads.push_back(E2.takePayload());
406
407 return E1;
408 }
409 if (E2.isA<ErrorList>()) {
410 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
411 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
412 return E2;
413 }
414 return Error(std::unique_ptr<ErrorList>(
415 new ErrorList(E1.takePayload(), E2.takePayload())));
416 }
417
418 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
419};
420
421/// Concatenate errors. The resulting Error is unchecked, and contains the
422/// ErrorInfo(s), if any, contained in E1, followed by the
423/// ErrorInfo(s), if any, contained in E2.
424inline Error joinErrors(Error E1, Error E2) {
425 return ErrorList::join(std::move(E1), std::move(E2));
426}
427
428/// Tagged union holding either a T or a Error.
429///
430/// This class parallels ErrorOr, but replaces error_code with Error. Since
431/// Error cannot be copied, this class replaces getError() with
432/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
433/// error class type.
434template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
435 template <class T1> friend class ExpectedAsOutParameter;
436 template <class OtherT> friend class Expected;
437
438 static const bool isRef = std::is_reference<T>::value;
439
440 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
441
442 using error_type = std::unique_ptr<ErrorInfoBase>;
443
444public:
445 using storage_type = typename std::conditional<isRef, wrap, T>::type;
446 using value_type = T;
447
448private:
449 using reference = typename std::remove_reference<T>::type &;
450 using const_reference = const typename std::remove_reference<T>::type &;
451 using pointer = typename std::remove_reference<T>::type *;
452 using const_pointer = const typename std::remove_reference<T>::type *;
453
454public:
455 /// Create an Expected<T> error value from the given Error.
456 Expected(Error Err)
457 : HasError(true)
458#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
459 // Expected is unchecked upon construction in Debug builds.
460 , Unchecked(true)
461#endif
462 {
463 assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value."
) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 463, __PRETTY_FUNCTION__))
;
464 new (getErrorStorage()) error_type(Err.takePayload());
465 }
466
467 /// Forbid to convert from Error::success() implicitly, this avoids having
468 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
469 /// but triggers the assertion above.
470 Expected(ErrorSuccess) = delete;
471
472 /// Create an Expected<T> success value from the given OtherT value, which
473 /// must be convertible to T.
474 template <typename OtherT>
475 Expected(OtherT &&Val,
476 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
477 * = nullptr)
478 : HasError(false)
479#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
480 // Expected is unchecked upon construction in Debug builds.
481 , Unchecked(true)
482#endif
483 {
484 new (getStorage()) storage_type(std::forward<OtherT>(Val));
485 }
486
487 /// Move construct an Expected<T> value.
488 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
489
490 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
491 /// must be convertible to T.
492 template <class OtherT>
493 Expected(Expected<OtherT> &&Other,
494 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
495 * = nullptr) {
496 moveConstruct(std::move(Other));
497 }
498
499 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
500 /// isn't convertible to T.
501 template <class OtherT>
502 explicit Expected(
503 Expected<OtherT> &&Other,
504 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
505 nullptr) {
506 moveConstruct(std::move(Other));
507 }
508
509 /// Move-assign from another Expected<T>.
510 Expected &operator=(Expected &&Other) {
511 moveAssign(std::move(Other));
512 return *this;
513 }
514
515 /// Destroy an Expected<T>.
516 ~Expected() {
517 assertIsChecked();
518 if (!HasError)
519 getStorage()->~storage_type();
520 else
521 getErrorStorage()->~error_type();
522 }
523
524 /// Return false if there is an error.
525 explicit operator bool() {
526#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
527 Unchecked = HasError;
528#endif
529 return !HasError;
530 }
531
532 /// Returns a reference to the stored T value.
533 reference get() {
534 assertIsChecked();
535 return *getStorage();
536 }
537
538 /// Returns a const reference to the stored T value.
539 const_reference get() const {
540 assertIsChecked();
541 return const_cast<Expected<T> *>(this)->get();
542 }
543
544 /// Check that this Expected<T> is an error of type ErrT.
545 template <typename ErrT> bool errorIsA() const {
546 return HasError && (*getErrorStorage())->template isA<ErrT>();
547 }
548
549 /// Take ownership of the stored error.
550 /// After calling this the Expected<T> is in an indeterminate state that can
551 /// only be safely destructed. No further calls (beside the destructor) should
552 /// be made on the Expected<T> vaule.
553 Error takeError() {
554#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
555 Unchecked = false;
556#endif
557 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
558 }
559
560 /// Returns a pointer to the stored T value.
561 pointer operator->() {
562 assertIsChecked();
563 return toPointer(getStorage());
564 }
565
566 /// Returns a const pointer to the stored T value.
567 const_pointer operator->() const {
568 assertIsChecked();
569 return toPointer(getStorage());
570 }
571
572 /// Returns a reference to the stored T value.
573 reference operator*() {
574 assertIsChecked();
575 return *getStorage();
576 }
577
578 /// Returns a const reference to the stored T value.
579 const_reference operator*() const {
580 assertIsChecked();
581 return *getStorage();
582 }
583
584private:
585 template <class T1>
586 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
587 return &a == &b;
588 }
589
590 template <class T1, class T2>
591 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
592 return false;
593 }
594
595 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
596 HasError = Other.HasError;
597#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
598 Unchecked = true;
599 Other.Unchecked = false;
600#endif
601
602 if (!HasError)
603 new (getStorage()) storage_type(std::move(*Other.getStorage()));
604 else
605 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
606 }
607
608 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
609 assertIsChecked();
610
611 if (compareThisIfSameType(*this, Other))
612 return;
613
614 this->~Expected();
615 new (this) Expected(std::move(Other));
616 }
617
618 pointer toPointer(pointer Val) { return Val; }
619
620 const_pointer toPointer(const_pointer Val) const { return Val; }
621
622 pointer toPointer(wrap *Val) { return &Val->get(); }
623
624 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
625
626 storage_type *getStorage() {
627 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 627, __PRETTY_FUNCTION__))
;
628 return reinterpret_cast<storage_type *>(TStorage.buffer);
629 }
630
631 const storage_type *getStorage() const {
632 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 632, __PRETTY_FUNCTION__))
;
633 return reinterpret_cast<const storage_type *>(TStorage.buffer);
634 }
635
636 error_type *getErrorStorage() {
637 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 637, __PRETTY_FUNCTION__))
;
638 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
639 }
640
641 const error_type *getErrorStorage() const {
642 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 642, __PRETTY_FUNCTION__))
;
643 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
644 }
645
646 // Used by ExpectedAsOutParameter to reset the checked flag.
647 void setUnchecked() {
648#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
649 Unchecked = true;
650#endif
651 }
652
653#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
654 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
655 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
656 void fatalUncheckedExpected() const {
657 dbgs() << "Expected<T> must be checked before access or destruction.\n";
658 if (HasError) {
659 dbgs() << "Unchecked Expected<T> contained error:\n";
660 (*getErrorStorage())->log(dbgs());
661 } else
662 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
663 "values in success mode must still be checked prior to being "
664 "destroyed).\n";
665 abort();
666 }
667#endif
668
669 void assertIsChecked() {
670#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
671 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
672 fatalUncheckedExpected();
673#endif
674 }
675
676 union {
677 AlignedCharArrayUnion<storage_type> TStorage;
678 AlignedCharArrayUnion<error_type> ErrorStorage;
679 };
680 bool HasError : 1;
681#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
682 bool Unchecked : 1;
683#endif
684};
685
686/// Report a serious error, calling any installed error handler. See
687/// ErrorHandling.h.
688LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
689 bool gen_crash_diag = true);
690
691/// Report a fatal error if Err is a failure value.
692///
693/// This function can be used to wrap calls to fallible functions ONLY when it
694/// is known that the Error will always be a success value. E.g.
695///
696/// @code{.cpp}
697/// // foo only attempts the fallible operation if DoFallibleOperation is
698/// // true. If DoFallibleOperation is false then foo always returns
699/// // Error::success().
700/// Error foo(bool DoFallibleOperation);
701///
702/// cantFail(foo(false));
703/// @endcode
704inline void cantFail(Error Err, const char *Msg = nullptr) {
705 if (Err) {
706 if (!Msg)
707 Msg = "Failure value returned from cantFail wrapped call";
708 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 708)
;
709 }
710}
711
712/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
713/// returns the contained value.
714///
715/// This function can be used to wrap calls to fallible functions ONLY when it
716/// is known that the Error will always be a success value. E.g.
717///
718/// @code{.cpp}
719/// // foo only attempts the fallible operation if DoFallibleOperation is
720/// // true. If DoFallibleOperation is false then foo always returns an int.
721/// Expected<int> foo(bool DoFallibleOperation);
722///
723/// int X = cantFail(foo(false));
724/// @endcode
725template <typename T>
726T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
727 if (ValOrErr)
728 return std::move(*ValOrErr);
729 else {
730 if (!Msg)
731 Msg = "Failure value returned from cantFail wrapped call";
732 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 732)
;
733 }
734}
735
736/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
737/// returns the contained reference.
738///
739/// This function can be used to wrap calls to fallible functions ONLY when it
740/// is known that the Error will always be a success value. E.g.
741///
742/// @code{.cpp}
743/// // foo only attempts the fallible operation if DoFallibleOperation is
744/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
745/// Expected<Bar&> foo(bool DoFallibleOperation);
746///
747/// Bar &X = cantFail(foo(false));
748/// @endcode
749template <typename T>
750T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
751 if (ValOrErr)
752 return *ValOrErr;
753 else {
754 if (!Msg)
755 Msg = "Failure value returned from cantFail wrapped call";
756 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 756)
;
757 }
758}
759
760/// Helper for testing applicability of, and applying, handlers for
761/// ErrorInfo types.
762template <typename HandlerT>
763class ErrorHandlerTraits
764 : public ErrorHandlerTraits<decltype(
765 &std::remove_reference<HandlerT>::type::operator())> {};
766
767// Specialization functions of the form 'Error (const ErrT&)'.
768template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
769public:
770 static bool appliesTo(const ErrorInfoBase &E) {
771 return E.template isA<ErrT>();
772 }
773
774 template <typename HandlerT>
775 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
776 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 776, __PRETTY_FUNCTION__))
;
777 return H(static_cast<ErrT &>(*E));
778 }
779};
780
781// Specialization functions of the form 'void (const ErrT&)'.
782template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
783public:
784 static bool appliesTo(const ErrorInfoBase &E) {
785 return E.template isA<ErrT>();
786 }
787
788 template <typename HandlerT>
789 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 790, __PRETTY_FUNCTION__))
;
791 H(static_cast<ErrT &>(*E));
792 return Error::success();
793 }
794};
795
796/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
797template <typename ErrT>
798class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
799public:
800 static bool appliesTo(const ErrorInfoBase &E) {
801 return E.template isA<ErrT>();
802 }
803
804 template <typename HandlerT>
805 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 806, __PRETTY_FUNCTION__))
;
807 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
808 return H(std::move(SubE));
809 }
810};
811
812/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
813template <typename ErrT>
814class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
815public:
816 static bool appliesTo(const ErrorInfoBase &E) {
817 return E.template isA<ErrT>();
818 }
819
820 template <typename HandlerT>
821 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
822 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 822, __PRETTY_FUNCTION__))
;
823 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
824 H(std::move(SubE));
825 return Error::success();
826 }
827};
828
829// Specialization for member functions of the form 'RetT (const ErrT&)'.
830template <typename C, typename RetT, typename ErrT>
831class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
832 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
833
834// Specialization for member functions of the form 'RetT (const ErrT&) const'.
835template <typename C, typename RetT, typename ErrT>
836class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
837 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
838
839// Specialization for member functions of the form 'RetT (const ErrT&)'.
840template <typename C, typename RetT, typename ErrT>
841class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
842 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
843
844// Specialization for member functions of the form 'RetT (const ErrT&) const'.
845template <typename C, typename RetT, typename ErrT>
846class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
847 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
848
849/// Specialization for member functions of the form
850/// 'RetT (std::unique_ptr<ErrT>)'.
851template <typename C, typename RetT, typename ErrT>
852class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
853 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
854
855/// Specialization for member functions of the form
856/// 'RetT (std::unique_ptr<ErrT>) const'.
857template <typename C, typename RetT, typename ErrT>
858class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
859 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
860
861inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
862 return Error(std::move(Payload));
863}
864
865template <typename HandlerT, typename... HandlerTs>
866Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
867 HandlerT &&Handler, HandlerTs &&... Handlers) {
868 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
869 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
870 std::move(Payload));
871 return handleErrorImpl(std::move(Payload),
872 std::forward<HandlerTs>(Handlers)...);
873}
874
875/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
876/// unhandled errors (or Errors returned by handlers) are re-concatenated and
877/// returned.
878/// Because this function returns an error, its result must also be checked
879/// or returned. If you intend to handle all errors use handleAllErrors
880/// (which returns void, and will abort() on unhandled errors) instead.
881template <typename... HandlerTs>
882Error handleErrors(Error E, HandlerTs &&... Hs) {
883 if (!E)
884 return Error::success();
885
886 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
887
888 if (Payload->isA<ErrorList>()) {
889 ErrorList &List = static_cast<ErrorList &>(*Payload);
890 Error R;
891 for (auto &P : List.Payloads)
892 R = ErrorList::join(
893 std::move(R),
894 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
895 return R;
896 }
897
898 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
899}
900
901/// Behaves the same as handleErrors, except that by contract all errors
902/// *must* be handled by the given handlers (i.e. there must be no remaining
903/// errors after running the handlers, or llvm_unreachable is called).
904template <typename... HandlerTs>
905void handleAllErrors(Error E, HandlerTs &&... Handlers) {
906 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
907}
908
909/// Check that E is a non-error, then drop it.
910/// If E is an error, llvm_unreachable will be called.
911inline void handleAllErrors(Error E) {
912 cantFail(std::move(E));
913}
914
915/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
916///
917/// If the incoming value is a success value it is returned unmodified. If it
918/// is a failure value then it the contained error is passed to handleErrors.
919/// If handleErrors is able to handle the error then the RecoveryPath functor
920/// is called to supply the final result. If handleErrors is not able to
921/// handle all errors then the unhandled errors are returned.
922///
923/// This utility enables the follow pattern:
924///
925/// @code{.cpp}
926/// enum FooStrategy { Aggressive, Conservative };
927/// Expected<Foo> foo(FooStrategy S);
928///
929/// auto ResultOrErr =
930/// handleExpected(
931/// foo(Aggressive),
932/// []() { return foo(Conservative); },
933/// [](AggressiveStrategyError&) {
934/// // Implicitly conusme this - we'll recover by using a conservative
935/// // strategy.
936/// });
937///
938/// @endcode
939template <typename T, typename RecoveryFtor, typename... HandlerTs>
940Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
941 HandlerTs &&... Handlers) {
942 if (ValOrErr)
943 return ValOrErr;
944
945 if (auto Err = handleErrors(ValOrErr.takeError(),
946 std::forward<HandlerTs>(Handlers)...))
947 return std::move(Err);
948
949 return RecoveryPath();
950}
951
952/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
953/// will be printed before the first one is logged. A newline will be printed
954/// after each error.
955///
956/// This is useful in the base level of your program to allow clean termination
957/// (allowing clean deallocation of resources, etc.), while reporting error
958/// information to the user.
959void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
960
961/// Write all error messages (if any) in E to a string. The newline character
962/// is used to separate error messages.
963inline std::string toString(Error E) {
964 SmallVector<std::string, 2> Errors;
965 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
966 Errors.push_back(EI.message());
967 });
968 return join(Errors.begin(), Errors.end(), "\n");
969}
970
971/// Consume a Error without doing anything. This method should be used
972/// only where an error can be considered a reasonable and expected return
973/// value.
974///
975/// Uses of this method are potentially indicative of design problems: If it's
976/// legitimate to do nothing while processing an "error", the error-producer
977/// might be more clearly refactored to return an Optional<T>.
978inline void consumeError(Error Err) {
979 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
980}
981
982/// Helper for converting an Error to a bool.
983///
984/// This method returns true if Err is in an error state, or false if it is
985/// in a success state. Puts Err in a checked state in both cases (unlike
986/// Error::operator bool(), which only does this for success states).
987inline bool errorToBool(Error Err) {
988 bool IsError = static_cast<bool>(Err);
989 if (IsError)
990 consumeError(std::move(Err));
991 return IsError;
992}
993
994/// Helper for Errors used as out-parameters.
995///
996/// This helper is for use with the Error-as-out-parameter idiom, where an error
997/// is passed to a function or method by reference, rather than being returned.
998/// In such cases it is helpful to set the checked bit on entry to the function
999/// so that the error can be written to (unchecked Errors abort on assignment)
1000/// and clear the checked bit on exit so that clients cannot accidentally forget
1001/// to check the result. This helper performs these actions automatically using
1002/// RAII:
1003///
1004/// @code{.cpp}
1005/// Result foo(Error &Err) {
1006/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1007/// // <body of foo>
1008/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1009/// }
1010/// @endcode
1011///
1012/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1013/// used with optional Errors (Error pointers that are allowed to be null). If
1014/// ErrorAsOutParameter took an Error reference, an instance would have to be
1015/// created inside every condition that verified that Error was non-null. By
1016/// taking an Error pointer we can just create one instance at the top of the
1017/// function.
1018class ErrorAsOutParameter {
1019public:
1020 ErrorAsOutParameter(Error *Err) : Err(Err) {
1021 // Raise the checked bit if Err is success.
1022 if (Err)
1023 (void)!!*Err;
1024 }
1025
1026 ~ErrorAsOutParameter() {
1027 // Clear the checked bit.
1028 if (Err && !*Err)
1029 *Err = Error::success();
1030 }
1031
1032private:
1033 Error *Err;
1034};
1035
1036/// Helper for Expected<T>s used as out-parameters.
1037///
1038/// See ErrorAsOutParameter.
1039template <typename T>
1040class ExpectedAsOutParameter {
1041public:
1042 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1043 : ValOrErr(ValOrErr) {
1044 if (ValOrErr)
1045 (void)!!*ValOrErr;
1046 }
1047
1048 ~ExpectedAsOutParameter() {
1049 if (ValOrErr)
1050 ValOrErr->setUnchecked();
1051 }
1052
1053private:
1054 Expected<T> *ValOrErr;
1055};
1056
1057/// This class wraps a std::error_code in a Error.
1058///
1059/// This is useful if you're writing an interface that returns a Error
1060/// (or Expected) and you want to call code that still returns
1061/// std::error_codes.
1062class ECError : public ErrorInfo<ECError> {
1063 friend Error errorCodeToError(std::error_code);
1064
1065public:
1066 void setErrorCode(std::error_code EC) { this->EC = EC; }
1067 std::error_code convertToErrorCode() const override { return EC; }
1068 void log(raw_ostream &OS) const override { OS << EC.message(); }
1069
1070 // Used by ErrorInfo::classID.
1071 static char ID;
1072
1073protected:
1074 ECError() = default;
1075 ECError(std::error_code EC) : EC(EC) {}
1076
1077 std::error_code EC;
1078};
1079
1080/// The value returned by this function can be returned from convertToErrorCode
1081/// for Error values where no sensible translation to std::error_code exists.
1082/// It should only be used in this situation, and should never be used where a
1083/// sensible conversion to std::error_code is available, as attempts to convert
1084/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1085///error to try to convert such a value).
1086std::error_code inconvertibleErrorCode();
1087
1088/// Helper for converting an std::error_code to a Error.
1089Error errorCodeToError(std::error_code EC);
1090
1091/// Helper for converting an ECError to a std::error_code.
1092///
1093/// This method requires that Err be Error() or an ECError, otherwise it
1094/// will trigger a call to abort().
1095std::error_code errorToErrorCode(Error Err);
1096
1097/// Convert an ErrorOr<T> to an Expected<T>.
1098template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1099 if (auto EC = EO.getError())
1100 return errorCodeToError(EC);
1101 return std::move(*EO);
1102}
1103
1104/// Convert an Expected<T> to an ErrorOr<T>.
1105template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1106 if (auto Err = E.takeError())
1107 return errorToErrorCode(std::move(Err));
1108 return std::move(*E);
1109}
1110
1111/// This class wraps a string in an Error.
1112///
1113/// StringError is useful in cases where the client is not expected to be able
1114/// to consume the specific error message programmatically (for example, if the
1115/// error message is to be presented to the user).
1116///
1117/// StringError can also be used when additional information is to be printed
1118/// along with a error_code message. Depending on the constructor called, this
1119/// class can either display:
1120/// 1. the error_code message (ECError behavior)
1121/// 2. a string
1122/// 3. the error_code message and a string
1123///
1124/// These behaviors are useful when subtyping is required; for example, when a
1125/// specific library needs an explicit error type. In the example below,
1126/// PDBError is derived from StringError:
1127///
1128/// @code{.cpp}
1129/// Expected<int> foo() {
1130/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1131/// "Additional information");
1132/// }
1133/// @endcode
1134///
1135class StringError : public ErrorInfo<StringError> {
1136public:
1137 static char ID;
1138
1139 // Prints EC + S and converts to EC
1140 StringError(std::error_code EC, const Twine &S = Twine());
1141
1142 // Prints S and converts to EC
1143 StringError(const Twine &S, std::error_code EC);
1144
1145 void log(raw_ostream &OS) const override;
1146 std::error_code convertToErrorCode() const override;
1147
1148 const std::string &getMessage() const { return Msg; }
1149
1150private:
1151 std::string Msg;
1152 std::error_code EC;
1153 const bool PrintMsgOnly = false;
1154};
1155
1156/// Create formatted StringError object.
1157template <typename... Ts>
1158Error createStringError(std::error_code EC, char const *Fmt,
1159 const Ts &... Vals) {
1160 std::string Buffer;
1161 raw_string_ostream Stream(Buffer);
1162 Stream << format(Fmt, Vals...);
1163 return make_error<StringError>(Stream.str(), EC);
1164}
1165
1166Error createStringError(std::error_code EC, char const *Msg);
1167
1168/// This class wraps a filename and another Error.
1169///
1170/// In some cases, an error needs to live along a 'source' name, in order to
1171/// show more detailed information to the user.
1172class FileError final : public ErrorInfo<FileError> {
1173
1174 friend Error createFileError(std::string, Error);
1175
1176public:
1177 void log(raw_ostream &OS) const override {
1178 assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()."
) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1178, __PRETTY_FUNCTION__))
;
1179 OS << "'" << FileName << "': ";
1180 Err->log(OS);
1181 }
1182
1183 Error takeError() { return Error(std::move(Err)); }
1184
1185 std::error_code convertToErrorCode() const override;
1186
1187 // Used by ErrorInfo::classID.
1188 static char ID;
1189
1190private:
1191 FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) {
1192 assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value."
) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1192, __PRETTY_FUNCTION__))
;
1193 assert(!F.empty() &&((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1194, __PRETTY_FUNCTION__))
1194 "The file name provided to FileError must not be empty.")((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1194, __PRETTY_FUNCTION__))
;
1195 FileName = F;
1196 Err = std::move(E);
1197 }
1198
1199 static Error build(std::string F, Error E) {
1200 return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload())));
1201 }
1202
1203 std::string FileName;
1204 std::unique_ptr<ErrorInfoBase> Err;
1205};
1206
1207/// Concatenate a source file path and/or name with an Error. The resulting
1208/// Error is unchecked.
1209inline Error createFileError(std::string F, Error E) {
1210 return FileError::build(F, std::move(E));
1211}
1212
1213Error createFileError(std::string F, ErrorSuccess) = delete;
1214
1215/// Helper for check-and-exit error handling.
1216///
1217/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1218///
1219class ExitOnError {
1220public:
1221 /// Create an error on exit helper.
1222 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1223 : Banner(std::move(Banner)),
1224 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1225
1226 /// Set the banner string for any errors caught by operator().
1227 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1228
1229 /// Set the exit-code mapper function.
1230 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1231 this->GetExitCode = std::move(GetExitCode);
1232 }
1233
1234 /// Check Err. If it's in a failure state log the error(s) and exit.
1235 void operator()(Error Err) const { checkError(std::move(Err)); }
1236
1237 /// Check E. If it's in a success state then return the contained value. If
1238 /// it's in a failure state log the error(s) and exit.
1239 template <typename T> T operator()(Expected<T> &&E) const {
1240 checkError(E.takeError());
1241 return std::move(*E);
1242 }
1243
1244 /// Check E. If it's in a success state then return the contained reference. If
1245 /// it's in a failure state log the error(s) and exit.
1246 template <typename T> T& operator()(Expected<T&> &&E) const {
1247 checkError(E.takeError());
1248 return *E;
1249 }
1250
1251private:
1252 void checkError(Error Err) const {
1253 if (Err) {
1254 int ExitCode = GetExitCode(Err);
1255 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1256 exit(ExitCode);
1257 }
1258 }
1259
1260 std::string Banner;
1261 std::function<int(const Error &)> GetExitCode;
1262};
1263
1264/// Conversion from Error to LLVMErrorRef for C error bindings.
1265inline LLVMErrorRef wrap(Error Err) {
1266 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1267}
1268
1269/// Conversion from LLVMErrorRef to Error for C error bindings.
1270inline Error unwrap(LLVMErrorRef ErrRef) {
1271 return Error(std::unique_ptr<ErrorInfoBase>(
1272 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1273}
1274
1275} // end namespace llvm
1276
1277#endif // LLVM_SUPPORT_ERROR_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- 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// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Config/abi-breaking.h"
25#include "llvm/Support/ErrorHandling.h"
26#include <algorithm>
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <cstdlib>
31#include <functional>
32#include <initializer_list>
33#include <iterator>
34#include <limits>
35#include <memory>
36#include <tuple>
37#include <type_traits>
38#include <utility>
39
40#ifdef EXPENSIVE_CHECKS
41#include <random> // for std::mt19937
42#endif
43
44namespace llvm {
45
46// Only used by compiler if both template types are the same. Useful when
47// using SFINAE to test for the existence of member functions.
48template <typename T, T> struct SameType;
49
50namespace detail {
51
52template <typename RangeT>
53using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
54
55template <typename RangeT>
56using ValueOfRange = typename std::remove_reference<decltype(
57 *std::begin(std::declval<RangeT &>()))>::type;
58
59} // end namespace detail
60
61//===----------------------------------------------------------------------===//
62// Extra additions to <type_traits>
63//===----------------------------------------------------------------------===//
64
65template <typename T>
66struct negation : std::integral_constant<bool, !bool(T::value)> {};
67
68template <typename...> struct conjunction : std::true_type {};
69template <typename B1> struct conjunction<B1> : B1 {};
70template <typename B1, typename... Bn>
71struct conjunction<B1, Bn...>
72 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
73
74//===----------------------------------------------------------------------===//
75// Extra additions to <functional>
76//===----------------------------------------------------------------------===//
77
78template <class Ty> struct identity {
79 using argument_type = Ty;
80
81 Ty &operator()(Ty &self) const {
82 return self;
83 }
84 const Ty &operator()(const Ty &self) const {
85 return self;
86 }
87};
88
89template <class Ty> struct less_ptr {
90 bool operator()(const Ty* left, const Ty* right) const {
91 return *left < *right;
92 }
93};
94
95template <class Ty> struct greater_ptr {
96 bool operator()(const Ty* left, const Ty* right) const {
97 return *right < *left;
98 }
99};
100
101/// An efficient, type-erasing, non-owning reference to a callable. This is
102/// intended for use as the type of a function parameter that is not used
103/// after the function in question returns.
104///
105/// This class does not own the callable, so it is not in general safe to store
106/// a function_ref.
107template<typename Fn> class function_ref;
108
109template<typename Ret, typename ...Params>
110class function_ref<Ret(Params...)> {
111 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
112 intptr_t callable;
113
114 template<typename Callable>
115 static Ret callback_fn(intptr_t callable, Params ...params) {
116 return (*reinterpret_cast<Callable*>(callable))(
117 std::forward<Params>(params)...);
118 }
119
120public:
121 function_ref() = default;
122 function_ref(std::nullptr_t) {}
123
124 template <typename Callable>
125 function_ref(Callable &&callable,
126 typename std::enable_if<
127 !std::is_same<typename std::remove_reference<Callable>::type,
128 function_ref>::value>::type * = nullptr)
129 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
130 callable(reinterpret_cast<intptr_t>(&callable)) {}
131
132 Ret operator()(Params ...params) const {
133 return callback(callable, std::forward<Params>(params)...);
134 }
135
136 operator bool() const { return callback; }
137};
138
139// deleter - Very very very simple method that is used to invoke operator
140// delete on something. It is used like this:
141//
142// for_each(V.begin(), B.end(), deleter<Interval>);
143template <class T>
144inline void deleter(T *Ptr) {
145 delete Ptr;
146}
147
148//===----------------------------------------------------------------------===//
149// Extra additions to <iterator>
150//===----------------------------------------------------------------------===//
151
152namespace adl_detail {
153
154using std::begin;
155
156template <typename ContainerTy>
157auto adl_begin(ContainerTy &&container)
158 -> decltype(begin(std::forward<ContainerTy>(container))) {
159 return begin(std::forward<ContainerTy>(container));
160}
161
162using std::end;
163
164template <typename ContainerTy>
165auto adl_end(ContainerTy &&container)
166 -> decltype(end(std::forward<ContainerTy>(container))) {
167 return end(std::forward<ContainerTy>(container));
168}
169
170using std::swap;
171
172template <typename T>
173void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
174 std::declval<T>()))) {
175 swap(std::forward<T>(lhs), std::forward<T>(rhs));
176}
177
178} // end namespace adl_detail
179
180template <typename ContainerTy>
181auto adl_begin(ContainerTy &&container)
182 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
183 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
184}
185
186template <typename ContainerTy>
187auto adl_end(ContainerTy &&container)
188 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
189 return adl_detail::adl_end(std::forward<ContainerTy>(container));
190}
191
192template <typename T>
193void adl_swap(T &&lhs, T &&rhs) noexcept(
194 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
195 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
196}
197
198// mapped_iterator - This is a simple iterator adapter that causes a function to
199// be applied whenever operator* is invoked on the iterator.
200
201template <typename ItTy, typename FuncTy,
202 typename FuncReturnTy =
203 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
204class mapped_iterator
205 : public iterator_adaptor_base<
206 mapped_iterator<ItTy, FuncTy>, ItTy,
207 typename std::iterator_traits<ItTy>::iterator_category,
208 typename std::remove_reference<FuncReturnTy>::type> {
209public:
210 mapped_iterator(ItTy U, FuncTy F)
211 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
212
213 ItTy getCurrent() { return this->I; }
214
215 FuncReturnTy operator*() { return F(*this->I); }
216
217private:
218 FuncTy F;
219};
220
221// map_iterator - Provide a convenient way to create mapped_iterators, just like
222// make_pair is useful for creating pairs...
223template <class ItTy, class FuncTy>
224inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
225 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
226}
227
228/// Helper to determine if type T has a member called rbegin().
229template <typename Ty> class has_rbegin_impl {
230 using yes = char[1];
231 using no = char[2];
232
233 template <typename Inner>
234 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
235
236 template <typename>
237 static no& test(...);
238
239public:
240 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
241};
242
243/// Metafunction to determine if T& or T has a member called rbegin().
244template <typename Ty>
245struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
246};
247
248// Returns an iterator_range over the given container which iterates in reverse.
249// Note that the container must have rbegin()/rend() methods for this to work.
250template <typename ContainerTy>
251auto reverse(ContainerTy &&C,
252 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
253 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
254 return make_range(C.rbegin(), C.rend());
255}
256
257// Returns a std::reverse_iterator wrapped around the given iterator.
258template <typename IteratorTy>
259std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
260 return std::reverse_iterator<IteratorTy>(It);
261}
262
263// Returns an iterator_range over the given container which iterates in reverse.
264// Note that the container must have begin()/end() methods which return
265// bidirectional iterators for this to work.
266template <typename ContainerTy>
267auto reverse(
268 ContainerTy &&C,
269 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
270 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
271 llvm::make_reverse_iterator(std::begin(C)))) {
272 return make_range(llvm::make_reverse_iterator(std::end(C)),
273 llvm::make_reverse_iterator(std::begin(C)));
274}
275
276/// An iterator adaptor that filters the elements of given inner iterators.
277///
278/// The predicate parameter should be a callable object that accepts the wrapped
279/// iterator's reference type and returns a bool. When incrementing or
280/// decrementing the iterator, it will call the predicate on each element and
281/// skip any where it returns false.
282///
283/// \code
284/// int A[] = { 1, 2, 3, 4 };
285/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
286/// // R contains { 1, 3 }.
287/// \endcode
288///
289/// Note: filter_iterator_base implements support for forward iteration.
290/// filter_iterator_impl exists to provide support for bidirectional iteration,
291/// conditional on whether the wrapped iterator supports it.
292template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
293class filter_iterator_base
294 : public iterator_adaptor_base<
295 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
296 WrappedIteratorT,
297 typename std::common_type<
298 IterTag, typename std::iterator_traits<
299 WrappedIteratorT>::iterator_category>::type> {
300 using BaseT = iterator_adaptor_base<
301 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
302 WrappedIteratorT,
303 typename std::common_type<
304 IterTag, typename std::iterator_traits<
305 WrappedIteratorT>::iterator_category>::type>;
306
307protected:
308 WrappedIteratorT End;
309 PredicateT Pred;
310
311 void findNextValid() {
312 while (this->I != End && !Pred(*this->I))
313 BaseT::operator++();
314 }
315
316 // Construct the iterator. The begin iterator needs to know where the end
317 // is, so that it can properly stop when it gets there. The end iterator only
318 // needs the predicate to support bidirectional iteration.
319 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
320 PredicateT Pred)
321 : BaseT(Begin), End(End), Pred(Pred) {
322 findNextValid();
323 }
324
325public:
326 using BaseT::operator++;
327
328 filter_iterator_base &operator++() {
329 BaseT::operator++();
330 findNextValid();
331 return *this;
332 }
333};
334
335/// Specialization of filter_iterator_base for forward iteration only.
336template <typename WrappedIteratorT, typename PredicateT,
337 typename IterTag = std::forward_iterator_tag>
338class filter_iterator_impl
339 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
340 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
341
342public:
343 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
344 PredicateT Pred)
345 : BaseT(Begin, End, Pred) {}
346};
347
348/// Specialization of filter_iterator_base for bidirectional iteration.
349template <typename WrappedIteratorT, typename PredicateT>
350class filter_iterator_impl<WrappedIteratorT, PredicateT,
351 std::bidirectional_iterator_tag>
352 : public filter_iterator_base<WrappedIteratorT, PredicateT,
353 std::bidirectional_iterator_tag> {
354 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
355 std::bidirectional_iterator_tag>;
356 void findPrevValid() {
357 while (!this->Pred(*this->I))
358 BaseT::operator--();
359 }
360
361public:
362 using BaseT::operator--;
363
364 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
365 PredicateT Pred)
366 : BaseT(Begin, End, Pred) {}
367
368 filter_iterator_impl &operator--() {
369 BaseT::operator--();
370 findPrevValid();
371 return *this;
372 }
373};
374
375namespace detail {
376
377template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
378 using type = std::forward_iterator_tag;
379};
380
381template <> struct fwd_or_bidi_tag_impl<true> {
382 using type = std::bidirectional_iterator_tag;
383};
384
385/// Helper which sets its type member to forward_iterator_tag if the category
386/// of \p IterT does not derive from bidirectional_iterator_tag, and to
387/// bidirectional_iterator_tag otherwise.
388template <typename IterT> struct fwd_or_bidi_tag {
389 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
390 std::bidirectional_iterator_tag,
391 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
392};
393
394} // namespace detail
395
396/// Defines filter_iterator to a suitable specialization of
397/// filter_iterator_impl, based on the underlying iterator's category.
398template <typename WrappedIteratorT, typename PredicateT>
399using filter_iterator = filter_iterator_impl<
400 WrappedIteratorT, PredicateT,
401 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
402
403/// Convenience function that takes a range of elements and a predicate,
404/// and return a new filter_iterator range.
405///
406/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
407/// lifetime of that temporary is not kept by the returned range object, and the
408/// temporary is going to be dropped on the floor after the make_iterator_range
409/// full expression that contains this function call.
410template <typename RangeT, typename PredicateT>
411iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
412make_filter_range(RangeT &&Range, PredicateT Pred) {
413 using FilterIteratorT =
414 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
415 return make_range(
416 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
417 std::end(std::forward<RangeT>(Range)), Pred),
418 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
419 std::end(std::forward<RangeT>(Range)), Pred));
420}
421
422/// A pseudo-iterator adaptor that is designed to implement "early increment"
423/// style loops.
424///
425/// This is *not a normal iterator* and should almost never be used directly. It
426/// is intended primarily to be used with range based for loops and some range
427/// algorithms.
428///
429/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
430/// somewhere between them. The constraints of these iterators are:
431///
432/// - On construction or after being incremented, it is comparable and
433/// dereferencable. It is *not* incrementable.
434/// - After being dereferenced, it is neither comparable nor dereferencable, it
435/// is only incrementable.
436///
437/// This means you can only dereference the iterator once, and you can only
438/// increment it once between dereferences.
439template <typename WrappedIteratorT>
440class early_inc_iterator_impl
441 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
442 WrappedIteratorT, std::input_iterator_tag> {
443 using BaseT =
444 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
445 WrappedIteratorT, std::input_iterator_tag>;
446
447 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
448
449protected:
450#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
451 bool IsEarlyIncremented = false;
452#endif
453
454public:
455 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
456
457 using BaseT::operator*;
458 typename BaseT::reference operator*() {
459#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
460 assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!")
? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 460, __PRETTY_FUNCTION__))
;
461 IsEarlyIncremented = true;
462#endif
463 return *(this->I)++;
464 }
465
466 using BaseT::operator++;
467 early_inc_iterator_impl &operator++() {
468#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
469 assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 469, __PRETTY_FUNCTION__))
;
470 IsEarlyIncremented = false;
471#endif
472 return *this;
473 }
474
475 using BaseT::operator==;
476 bool operator==(const early_inc_iterator_impl &RHS) const {
477#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
478 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 478, __PRETTY_FUNCTION__))
;
479#endif
480 return BaseT::operator==(RHS);
481 }
482};
483
484/// Make a range that does early increment to allow mutation of the underlying
485/// range without disrupting iteration.
486///
487/// The underlying iterator will be incremented immediately after it is
488/// dereferenced, allowing deletion of the current node or insertion of nodes to
489/// not disrupt iteration provided they do not invalidate the *next* iterator --
490/// the current iterator can be invalidated.
491///
492/// This requires a very exact pattern of use that is only really suitable to
493/// range based for loops and other range algorithms that explicitly guarantee
494/// to dereference exactly once each element, and to increment exactly once each
495/// element.
496template <typename RangeT>
497iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
498make_early_inc_range(RangeT &&Range) {
499 using EarlyIncIteratorT =
500 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
501 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
502 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
503}
504
505// forward declarations required by zip_shortest/zip_first
506template <typename R, typename UnaryPredicate>
507bool all_of(R &&range, UnaryPredicate P);
508
509template <size_t... I> struct index_sequence;
510
511template <class... Ts> struct index_sequence_for;
512
513namespace detail {
514
515using std::declval;
516
517// We have to alias this since inlining the actual type at the usage site
518// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
519template<typename... Iters> struct ZipTupleType {
520 using type = std::tuple<decltype(*declval<Iters>())...>;
521};
522
523template <typename ZipType, typename... Iters>
524using zip_traits = iterator_facade_base<
525 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
526 typename std::iterator_traits<
527 Iters>::iterator_category...>::type,
528 // ^ TODO: Implement random access methods.
529 typename ZipTupleType<Iters...>::type,
530 typename std::iterator_traits<typename std::tuple_element<
531 0, std::tuple<Iters...>>::type>::difference_type,
532 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
533 // inner iterators have the same difference_type. It would fail if, for
534 // instance, the second field's difference_type were non-numeric while the
535 // first is.
536 typename ZipTupleType<Iters...>::type *,
537 typename ZipTupleType<Iters...>::type>;
538
539template <typename ZipType, typename... Iters>
540struct zip_common : public zip_traits<ZipType, Iters...> {
541 using Base = zip_traits<ZipType, Iters...>;
542 using value_type = typename Base::value_type;
543
544 std::tuple<Iters...> iterators;
545
546protected:
547 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
548 return value_type(*std::get<Ns>(iterators)...);
549 }
550
551 template <size_t... Ns>
552 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
553 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
554 }
555
556 template <size_t... Ns>
557 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
558 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
559 }
560
561public:
562 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
563
564 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
565
566 const value_type operator*() const {
567 return deref(index_sequence_for<Iters...>{});
568 }
569
570 ZipType &operator++() {
571 iterators = tup_inc(index_sequence_for<Iters...>{});
572 return *reinterpret_cast<ZipType *>(this);
573 }
574
575 ZipType &operator--() {
576 static_assert(Base::IsBidirectional,
577 "All inner iterators must be at least bidirectional.");
578 iterators = tup_dec(index_sequence_for<Iters...>{});
579 return *reinterpret_cast<ZipType *>(this);
580 }
581};
582
583template <typename... Iters>
584struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
585 using Base = zip_common<zip_first<Iters...>, Iters...>;
586
587 bool operator==(const zip_first<Iters...> &other) const {
588 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
589 }
590
591 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
592};
593
594template <typename... Iters>
595class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
596 template <size_t... Ns>
597 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
598 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
599 std::get<Ns>(other.iterators)...},
600 identity<bool>{});
601 }
602
603public:
604 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
605
606 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
607
608 bool operator==(const zip_shortest<Iters...> &other) const {
609 return !test(other, index_sequence_for<Iters...>{});
610 }
611};
612
613template <template <typename...> class ItType, typename... Args> class zippy {
614public:
615 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
616 using iterator_category = typename iterator::iterator_category;
617 using value_type = typename iterator::value_type;
618 using difference_type = typename iterator::difference_type;
619 using pointer = typename iterator::pointer;
620 using reference = typename iterator::reference;
621
622private:
623 std::tuple<Args...> ts;
624
625 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
626 return iterator(std::begin(std::get<Ns>(ts))...);
627 }
628 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
629 return iterator(std::end(std::get<Ns>(ts))...);
630 }
631
632public:
633 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
634
635 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
636 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
637};
638
639} // end namespace detail
640
641/// zip iterator for two or more iteratable types.
642template <typename T, typename U, typename... Args>
643detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
644 Args &&... args) {
645 return detail::zippy<detail::zip_shortest, T, U, Args...>(
646 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
647}
648
649/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
650/// be the shortest.
651template <typename T, typename U, typename... Args>
652detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
653 Args &&... args) {
654 return detail::zippy<detail::zip_first, T, U, Args...>(
655 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
656}
657
658/// Iterator wrapper that concatenates sequences together.
659///
660/// This can concatenate different iterators, even with different types, into
661/// a single iterator provided the value types of all the concatenated
662/// iterators expose `reference` and `pointer` types that can be converted to
663/// `ValueT &` and `ValueT *` respectively. It doesn't support more
664/// interesting/customized pointer or reference types.
665///
666/// Currently this only supports forward or higher iterator categories as
667/// inputs and always exposes a forward iterator interface.
668template <typename ValueT, typename... IterTs>
669class concat_iterator
670 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
671 std::forward_iterator_tag, ValueT> {
672 using BaseT = typename concat_iterator::iterator_facade_base;
673
674 /// We store both the current and end iterators for each concatenated
675 /// sequence in a tuple of pairs.
676 ///
677 /// Note that something like iterator_range seems nice at first here, but the
678 /// range properties are of little benefit and end up getting in the way
679 /// because we need to do mutation on the current iterators.
680 std::tuple<IterTs...> Begins;
681 std::tuple<IterTs...> Ends;
682
683 /// Attempts to increment a specific iterator.
684 ///
685 /// Returns true if it was able to increment the iterator. Returns false if
686 /// the iterator is already at the end iterator.
687 template <size_t Index> bool incrementHelper() {
688 auto &Begin = std::get<Index>(Begins);
689 auto &End = std::get<Index>(Ends);
690 if (Begin == End)
691 return false;
692
693 ++Begin;
694 return true;
695 }
696
697 /// Increments the first non-end iterator.
698 ///
699 /// It is an error to call this with all iterators at the end.
700 template <size_t... Ns> void increment(index_sequence<Ns...>) {
701 // Build a sequence of functions to increment each iterator if possible.
702 bool (concat_iterator::*IncrementHelperFns[])() = {
703 &concat_iterator::incrementHelper<Ns>...};
704
705 // Loop over them, and stop as soon as we succeed at incrementing one.
706 for (auto &IncrementHelperFn : IncrementHelperFns)
707 if ((this->*IncrementHelperFn)())
708 return;
709
710 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 710)
;
711 }
712
713 /// Returns null if the specified iterator is at the end. Otherwise,
714 /// dereferences the iterator and returns the address of the resulting
715 /// reference.
716 template <size_t Index> ValueT *getHelper() const {
717 auto &Begin = std::get<Index>(Begins);
718 auto &End = std::get<Index>(Ends);
719 if (Begin == End)
720 return nullptr;
721
722 return &*Begin;
723 }
724
725 /// Finds the first non-end iterator, dereferences, and returns the resulting
726 /// reference.
727 ///
728 /// It is an error to call this with all iterators at the end.
729 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
730 // Build a sequence of functions to get from iterator if possible.
731 ValueT *(concat_iterator::*GetHelperFns[])() const = {
732 &concat_iterator::getHelper<Ns>...};
733
734 // Loop over them, and return the first result we find.
735 for (auto &GetHelperFn : GetHelperFns)
736 if (ValueT *P = (this->*GetHelperFn)())
737 return *P;
738
739 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 739)
;
740 }
741
742public:
743 /// Constructs an iterator from a squence of ranges.
744 ///
745 /// We need the full range to know how to switch between each of the
746 /// iterators.
747 template <typename... RangeTs>
748 explicit concat_iterator(RangeTs &&... Ranges)
749 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
750
751 using BaseT::operator++;
752
753 concat_iterator &operator++() {
754 increment(index_sequence_for<IterTs...>());
755 return *this;
756 }
757
758 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
759
760 bool operator==(const concat_iterator &RHS) const {
761 return Begins == RHS.Begins && Ends == RHS.Ends;
762 }
763};
764
765namespace detail {
766
767/// Helper to store a sequence of ranges being concatenated and access them.
768///
769/// This is designed to facilitate providing actual storage when temporaries
770/// are passed into the constructor such that we can use it as part of range
771/// based for loops.
772template <typename ValueT, typename... RangeTs> class concat_range {
773public:
774 using iterator =
775 concat_iterator<ValueT,
776 decltype(std::begin(std::declval<RangeTs &>()))...>;
777
778private:
779 std::tuple<RangeTs...> Ranges;
780
781 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
782 return iterator(std::get<Ns>(Ranges)...);
783 }
784 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
785 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
786 std::end(std::get<Ns>(Ranges)))...);
787 }
788
789public:
790 concat_range(RangeTs &&... Ranges)
791 : Ranges(std::forward<RangeTs>(Ranges)...) {}
792
793 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
794 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
795};
796
797} // end namespace detail
798
799/// Concatenated range across two or more ranges.
800///
801/// The desired value type must be explicitly specified.
802template <typename ValueT, typename... RangeTs>
803detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
804 static_assert(sizeof...(RangeTs) > 1,
805 "Need more than one range to concatenate!");
806 return detail::concat_range<ValueT, RangeTs...>(
807 std::forward<RangeTs>(Ranges)...);
808}
809
810//===----------------------------------------------------------------------===//
811// Extra additions to <utility>
812//===----------------------------------------------------------------------===//
813
814/// Function object to check whether the first component of a std::pair
815/// compares less than the first component of another std::pair.
816struct less_first {
817 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
818 return lhs.first < rhs.first;
819 }
820};
821
822/// Function object to check whether the second component of a std::pair
823/// compares less than the second component of another std::pair.
824struct less_second {
825 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
826 return lhs.second < rhs.second;
827 }
828};
829
830/// \brief Function object to apply a binary function to the first component of
831/// a std::pair.
832template<typename FuncTy>
833struct on_first {
834 FuncTy func;
835
836 template <typename T>
837 auto operator()(const T &lhs, const T &rhs) const
838 -> decltype(func(lhs.first, rhs.first)) {
839 return func(lhs.first, rhs.first);
840 }
841};
842
843// A subset of N3658. More stuff can be added as-needed.
844
845/// Represents a compile-time sequence of integers.
846template <class T, T... I> struct integer_sequence {
847 using value_type = T;
848
849 static constexpr size_t size() { return sizeof...(I); }
850};
851
852/// Alias for the common case of a sequence of size_ts.
853template <size_t... I>
854struct index_sequence : integer_sequence<std::size_t, I...> {};
855
856template <std::size_t N, std::size_t... I>
857struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
858template <std::size_t... I>
859struct build_index_impl<0, I...> : index_sequence<I...> {};
860
861/// Creates a compile-time integer sequence for a parameter pack.
862template <class... Ts>
863struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
864
865/// Utility type to build an inheritance chain that makes it easy to rank
866/// overload candidates.
867template <int N> struct rank : rank<N - 1> {};
868template <> struct rank<0> {};
869
870/// traits class for checking whether type T is one of any of the given
871/// types in the variadic list.
872template <typename T, typename... Ts> struct is_one_of {
873 static const bool value = false;
874};
875
876template <typename T, typename U, typename... Ts>
877struct is_one_of<T, U, Ts...> {
878 static const bool value =
879 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
880};
881
882/// traits class for checking whether type T is a base class for all
883/// the given types in the variadic list.
884template <typename T, typename... Ts> struct are_base_of {
885 static const bool value = true;
886};
887
888template <typename T, typename U, typename... Ts>
889struct are_base_of<T, U, Ts...> {
890 static const bool value =
891 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
892};
893
894//===----------------------------------------------------------------------===//
895// Extra additions for arrays
896//===----------------------------------------------------------------------===//
897
898/// Find the length of an array.
899template <class T, std::size_t N>
900constexpr inline size_t array_lengthof(T (&)[N]) {
901 return N;
902}
903
904/// Adapt std::less<T> for array_pod_sort.
905template<typename T>
906inline int array_pod_sort_comparator(const void *P1, const void *P2) {
907 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
908 *reinterpret_cast<const T*>(P2)))
909 return -1;
910 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
911 *reinterpret_cast<const T*>(P1)))
912 return 1;
913 return 0;
914}
915
916/// get_array_pod_sort_comparator - This is an internal helper function used to
917/// get type deduction of T right.
918template<typename T>
919inline int (*get_array_pod_sort_comparator(const T &))
920 (const void*, const void*) {
921 return array_pod_sort_comparator<T>;
922}
923
924/// array_pod_sort - This sorts an array with the specified start and end
925/// extent. This is just like std::sort, except that it calls qsort instead of
926/// using an inlined template. qsort is slightly slower than std::sort, but
927/// most sorts are not performance critical in LLVM and std::sort has to be
928/// template instantiated for each type, leading to significant measured code
929/// bloat. This function should generally be used instead of std::sort where
930/// possible.
931///
932/// This function assumes that you have simple POD-like types that can be
933/// compared with std::less and can be moved with memcpy. If this isn't true,
934/// you should use std::sort.
935///
936/// NOTE: If qsort_r were portable, we could allow a custom comparator and
937/// default to std::less.
938template<class IteratorTy>
939inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
940 // Don't inefficiently call qsort with one element or trigger undefined
941 // behavior with an empty sequence.
942 auto NElts = End - Start;
943 if (NElts <= 1) return;
944#ifdef EXPENSIVE_CHECKS
945 std::mt19937 Generator(std::random_device{}());
946 std::shuffle(Start, End, Generator);
947#endif
948 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
949}
950
951template <class IteratorTy>
952inline void array_pod_sort(
953 IteratorTy Start, IteratorTy End,
954 int (*Compare)(
955 const typename std::iterator_traits<IteratorTy>::value_type *,
956 const typename std::iterator_traits<IteratorTy>::value_type *)) {
957 // Don't inefficiently call qsort with one element or trigger undefined
958 // behavior with an empty sequence.
959 auto NElts = End - Start;
960 if (NElts <= 1) return;
961#ifdef EXPENSIVE_CHECKS
962 std::mt19937 Generator(std::random_device{}());
963 std::shuffle(Start, End, Generator);
964#endif
965 qsort(&*Start, NElts, sizeof(*Start),
966 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
967}
968
969// Provide wrappers to std::sort which shuffle the elements before sorting
970// to help uncover non-deterministic behavior (PR35135).
971template <typename IteratorTy>
972inline void sort(IteratorTy Start, IteratorTy End) {
973#ifdef EXPENSIVE_CHECKS
974 std::mt19937 Generator(std::random_device{}());
975 std::shuffle(Start, End, Generator);
976#endif
977 std::sort(Start, End);
978}
979
980template <typename Container> inline void sort(Container &&C) {
981 llvm::sort(adl_begin(C), adl_end(C));
982}
983
984template <typename IteratorTy, typename Compare>
985inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
986#ifdef EXPENSIVE_CHECKS
987 std::mt19937 Generator(std::random_device{}());
988 std::shuffle(Start, End, Generator);
989#endif
990 std::sort(Start, End, Comp);
991}
992
993template <typename Container, typename Compare>
994inline void sort(Container &&C, Compare Comp) {
995 llvm::sort(adl_begin(C), adl_end(C), Comp);
996}
997
998//===----------------------------------------------------------------------===//
999// Extra additions to <algorithm>
1000//===----------------------------------------------------------------------===//
1001
1002/// For a container of pointers, deletes the pointers and then clears the
1003/// container.
1004template<typename Container>
1005void DeleteContainerPointers(Container &C) {
1006 for (auto V : C)
1007 delete V;
1008 C.clear();
1009}
1010
1011/// In a container of pairs (usually a map) whose second element is a pointer,
1012/// deletes the second elements and then clears the container.
1013template<typename Container>
1014void DeleteContainerSeconds(Container &C) {
1015 for (auto &V : C)
1016 delete V.second;
1017 C.clear();
1018}
1019
1020/// Get the size of a range. This is a wrapper function around std::distance
1021/// which is only enabled when the operation is O(1).
1022template <typename R>
1023auto size(R &&Range, typename std::enable_if<
1024 std::is_same<typename std::iterator_traits<decltype(
1025 Range.begin())>::iterator_category,
1026 std::random_access_iterator_tag>::value,
1027 void>::type * = nullptr)
1028 -> decltype(std::distance(Range.begin(), Range.end())) {
1029 return std::distance(Range.begin(), Range.end());
1030}
1031
1032/// Provide wrappers to std::for_each which take ranges instead of having to
1033/// pass begin/end explicitly.
1034template <typename R, typename UnaryPredicate>
1035UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1036 return std::for_each(adl_begin(Range), adl_end(Range), P);
1037}
1038
1039/// Provide wrappers to std::all_of which take ranges instead of having to pass
1040/// begin/end explicitly.
1041template <typename R, typename UnaryPredicate>
1042bool all_of(R &&Range, UnaryPredicate P) {
1043 return std::all_of(adl_begin(Range), adl_end(Range), P);
1044}
1045
1046/// Provide wrappers to std::any_of which take ranges instead of having to pass
1047/// begin/end explicitly.
1048template <typename R, typename UnaryPredicate>
1049bool any_of(R &&Range, UnaryPredicate P) {
1050 return std::any_of(adl_begin(Range), adl_end(Range), P);
1051}
1052
1053/// Provide wrappers to std::none_of which take ranges instead of having to pass
1054/// begin/end explicitly.
1055template <typename R, typename UnaryPredicate>
1056bool none_of(R &&Range, UnaryPredicate P) {
1057 return std::none_of(adl_begin(Range), adl_end(Range), P);
1058}
1059
1060/// Provide wrappers to std::find which take ranges instead of having to pass
1061/// begin/end explicitly.
1062template <typename R, typename T>
1063auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1064 return std::find(adl_begin(Range), adl_end(Range), Val);
1065}
1066
1067/// Provide wrappers to std::find_if which take ranges instead of having to pass
1068/// begin/end explicitly.
1069template <typename R, typename UnaryPredicate>
1070auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1071 return std::find_if(adl_begin(Range), adl_end(Range), P);
1072}
1073
1074template <typename R, typename UnaryPredicate>
1075auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1076 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1077}
1078
1079/// Provide wrappers to std::remove_if which take ranges instead of having to
1080/// pass begin/end explicitly.
1081template <typename R, typename UnaryPredicate>
1082auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1083 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1084}
1085
1086/// Provide wrappers to std::copy_if which take ranges instead of having to
1087/// pass begin/end explicitly.
1088template <typename R, typename OutputIt, typename UnaryPredicate>
1089OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1090 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1091}
1092
1093template <typename R, typename OutputIt>
1094OutputIt copy(R &&Range, OutputIt Out) {
1095 return std::copy(adl_begin(Range), adl_end(Range), Out);
1096}
1097
1098/// Wrapper function around std::find to detect if an element exists
1099/// in a container.
1100template <typename R, typename E>
1101bool is_contained(R &&Range, const E &Element) {
1102 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1103}
1104
1105/// Wrapper function around std::count to count the number of times an element
1106/// \p Element occurs in the given range \p Range.
1107template <typename R, typename E>
1108auto count(R &&Range, const E &Element) ->
1109 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1110 return std::count(adl_begin(Range), adl_end(Range), Element);
1111}
1112
1113/// Wrapper function around std::count_if to count the number of times an
1114/// element satisfying a given predicate occurs in a range.
1115template <typename R, typename UnaryPredicate>
1116auto count_if(R &&Range, UnaryPredicate P) ->
1117 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1118 return std::count_if(adl_begin(Range), adl_end(Range), P);
1119}
1120
1121/// Wrapper function around std::transform to apply a function to a range and
1122/// store the result elsewhere.
1123template <typename R, typename OutputIt, typename UnaryPredicate>
1124OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1125 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1126}
1127
1128/// Provide wrappers to std::partition which take ranges instead of having to
1129/// pass begin/end explicitly.
1130template <typename R, typename UnaryPredicate>
1131auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1132 return std::partition(adl_begin(Range), adl_end(Range), P);
1133}
1134
1135/// Provide wrappers to std::lower_bound which take ranges instead of having to
1136/// pass begin/end explicitly.
1137template <typename R, typename ForwardIt>
1138auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1139 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
1140}
1141
1142template <typename R, typename ForwardIt, typename Compare>
1143auto lower_bound(R &&Range, ForwardIt I, Compare C)
1144 -> decltype(adl_begin(Range)) {
1145 return std::lower_bound(adl_begin(Range), adl_end(Range), I, C);
1146}
1147
1148/// Provide wrappers to std::upper_bound which take ranges instead of having to
1149/// pass begin/end explicitly.
1150template <typename R, typename ForwardIt>
1151auto upper_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1152 return std::upper_bound(adl_begin(Range), adl_end(Range), I);
1153}
1154
1155template <typename R, typename ForwardIt, typename Compare>
1156auto upper_bound(R &&Range, ForwardIt I, Compare C)
1157 -> decltype(adl_begin(Range)) {
1158 return std::upper_bound(adl_begin(Range), adl_end(Range), I, C);
1159}
1160/// Wrapper function around std::equal to detect if all elements
1161/// in a container are same.
1162template <typename R>
1163bool is_splat(R &&Range) {
1164 size_t range_size = size(Range);
1165 return range_size != 0 && (range_size == 1 ||
1166 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1167}
1168
1169/// Given a range of type R, iterate the entire range and return a
1170/// SmallVector with elements of the vector. This is useful, for example,
1171/// when you want to iterate a range and then sort the results.
1172template <unsigned Size, typename R>
1173SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
1174to_vector(R &&Range) {
1175 return {adl_begin(Range), adl_end(Range)};
1176}
1177
1178/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1179/// `erase_if` which is equivalent to:
1180///
1181/// C.erase(remove_if(C, pred), C.end());
1182///
1183/// This version works for any container with an erase method call accepting
1184/// two iterators.
1185template <typename Container, typename UnaryPredicate>
1186void erase_if(Container &C, UnaryPredicate P) {
1187 C.erase(remove_if(C, P), C.end());
1188}
1189
1190//===----------------------------------------------------------------------===//
1191// Extra additions to <memory>
1192//===----------------------------------------------------------------------===//
1193
1194// Implement make_unique according to N3656.
1195
1196/// Constructs a `new T()` with the given args and returns a
1197/// `unique_ptr<T>` which owns the object.
1198///
1199/// Example:
1200///
1201/// auto p = make_unique<int>();
1202/// auto p = make_unique<std::tuple<int, int>>(0, 1);
1203template <class T, class... Args>
1204typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1205make_unique(Args &&... args) {
1206 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
5
Memory is allocated
1207}
1208
1209/// Constructs a `new T[n]` with the given args and returns a
1210/// `unique_ptr<T[]>` which owns the object.
1211///
1212/// \param n size of the new array.
1213///
1214/// Example:
1215///
1216/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1217template <class T>
1218typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1219 std::unique_ptr<T>>::type
1220make_unique(size_t n) {
1221 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1222}
1223
1224/// This function isn't used and is only here to provide better compile errors.
1225template <class T, class... Args>
1226typename std::enable_if<std::extent<T>::value != 0>::type
1227make_unique(Args &&...) = delete;
1228
1229struct FreeDeleter {
1230 void operator()(void* v) {
1231 ::free(v);
1232 }
1233};
1234
1235template<typename First, typename Second>
1236struct pair_hash {
1237 size_t operator()(const std::pair<First, Second> &P) const {
1238 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1239 }
1240};
1241
1242/// A functor like C++14's std::less<void> in its absence.
1243struct less {
1244 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1245 return std::forward<A>(a) < std::forward<B>(b);
1246 }
1247};
1248
1249/// A functor like C++14's std::equal<void> in its absence.
1250struct equal {
1251 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1252 return std::forward<A>(a) == std::forward<B>(b);
1253 }
1254};
1255
1256/// Binary functor that adapts to any other binary functor after dereferencing
1257/// operands.
1258template <typename T> struct deref {
1259 T func;
1260
1261 // Could be further improved to cope with non-derivable functors and
1262 // non-binary functors (should be a variadic template member function
1263 // operator()).
1264 template <typename A, typename B>
1265 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1266 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1266, __PRETTY_FUNCTION__))
;
1267 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1267, __PRETTY_FUNCTION__))
;
1268 return func(*lhs, *rhs);
1269 }
1270};
1271
1272namespace detail {
1273
1274template <typename R> class enumerator_iter;
1275
1276template <typename R> struct result_pair {
1277 friend class enumerator_iter<R>;
1278
1279 result_pair() = default;
1280 result_pair(std::size_t Index, IterOfRange<R> Iter)
1281 : Index(Index), Iter(Iter) {}
1282
1283 result_pair<R> &operator=(const result_pair<R> &Other) {
1284 Index = Other.Index;
1285 Iter = Other.Iter;
1286 return *this;
1287 }
1288
1289 std::size_t index() const { return Index; }
1290 const ValueOfRange<R> &value() const { return *Iter; }
1291 ValueOfRange<R> &value() { return *Iter; }
1292
1293private:
1294 std::size_t Index = std::numeric_limits<std::size_t>::max();
1295 IterOfRange<R> Iter;
1296};
1297
1298template <typename R>
1299class enumerator_iter
1300 : public iterator_facade_base<
1301 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1302 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1303 typename std::iterator_traits<IterOfRange<R>>::pointer,
1304 typename std::iterator_traits<IterOfRange<R>>::reference> {
1305 using result_type = result_pair<R>;
1306
1307public:
1308 explicit enumerator_iter(IterOfRange<R> EndIter)
1309 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1310
1311 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1312 : Result(Index, Iter) {}
1313
1314 result_type &operator*() { return Result; }
1315 const result_type &operator*() const { return Result; }
1316
1317 enumerator_iter<R> &operator++() {
1318 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1318, __PRETTY_FUNCTION__))
;
1319 ++Result.Iter;
1320 ++Result.Index;
1321 return *this;
1322 }
1323
1324 bool operator==(const enumerator_iter<R> &RHS) const {
1325 // Don't compare indices here, only iterators. It's possible for an end
1326 // iterator to have different indices depending on whether it was created
1327 // by calling std::end() versus incrementing a valid iterator.
1328 return Result.Iter == RHS.Result.Iter;
1329 }
1330
1331 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1332 Result = Other.Result;
1333 return *this;
1334 }
1335
1336private:
1337 result_type Result;
1338};
1339
1340template <typename R> class enumerator {
1341public:
1342 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1343
1344 enumerator_iter<R> begin() {
1345 return enumerator_iter<R>(0, std::begin(TheRange));
1346 }
1347
1348 enumerator_iter<R> end() {
1349 return enumerator_iter<R>(std::end(TheRange));
1350 }
1351
1352private:
1353 R TheRange;
1354};
1355
1356} // end namespace detail
1357
1358/// Given an input range, returns a new range whose values are are pair (A,B)
1359/// such that A is the 0-based index of the item in the sequence, and B is
1360/// the value from the original sequence. Example:
1361///
1362/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1363/// for (auto X : enumerate(Items)) {
1364/// printf("Item %d - %c\n", X.index(), X.value());
1365/// }
1366///
1367/// Output:
1368/// Item 0 - A
1369/// Item 1 - B
1370/// Item 2 - C
1371/// Item 3 - D
1372///
1373template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1374 return detail::enumerator<R>(std::forward<R>(TheRange));
1375}
1376
1377namespace detail {
1378
1379template <typename F, typename Tuple, std::size_t... I>
1380auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1381 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1382 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1383}
1384
1385} // end namespace detail
1386
1387/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1388/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1389/// return the result.
1390template <typename F, typename Tuple>
1391auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1392 std::forward<F>(f), std::forward<Tuple>(t),
1393 build_index_impl<
1394 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1395 using Indices = build_index_impl<
1396 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1397
1398 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1399 Indices{});
1400}
1401
1402} // end namespace llvm
1403
1404#endif // LLVM_ADT_STLEXTRAS_H