LLDB mainline
ProcessLauncherPosixFork.cpp
Go to the documentation of this file.
1//===-- ProcessLauncherPosixFork.cpp --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "lldb/Host/Host.h"
13#include "lldb/Host/Pipe.h"
16#include "lldb/Utility/Log.h"
17#include "llvm/Support/Errno.h"
18
19#include <algorithm>
20#include <climits>
21#include <fcntl.h>
22#include <sys/ptrace.h>
23#include <sys/wait.h>
24#include <unistd.h>
25
26#include <csignal>
27#include <sstream>
28
29#if defined(__FreeBSD__)
30#include <sys/param.h>
31#endif
32
33#if defined(__linux__)
34#include <sys/personality.h>
35#endif
36
37using namespace lldb;
38using namespace lldb_private;
39
40// Begin code running in the child process
41// NB: This code needs to be async-signal safe, since we're invoking fork from
42// multithreaded contexts.
43
44static void write_string(int error_fd, const char *str) {
45 int r = write(error_fd, str, strlen(str));
46 (void)r;
47}
48
49[[noreturn]] static void ExitWithError(int error_fd, const char *operation) {
50 int err = errno;
51 write_string(error_fd, operation);
52 write_string(error_fd, " failed: ");
53 // strerror is not guaranteed to be async-signal safe, but it usually is.
54 write_string(error_fd, strerror(err));
55 _exit(1);
56}
57
58static void DisableASLR(int error_fd) {
59#if defined(__linux__)
60 const unsigned long personality_get_current = 0xffffffff;
61 int value = personality(personality_get_current);
62 if (value == -1)
63 ExitWithError(error_fd, "personality get");
64
65 value = personality(ADDR_NO_RANDOMIZE | value);
66 if (value == -1)
67 ExitWithError(error_fd, "personality set");
68#endif
69}
70
71static void DupDescriptor(int error_fd, const char *file, int fd, int flags) {
72 int target_fd = FileSystem::Instance().Open(file, flags, 0666);
73
74 if (target_fd == -1)
75 ExitWithError(error_fd, "DupDescriptor-open");
76
77 if (target_fd == fd)
78 return;
79
80 if (::dup2(target_fd, fd) == -1)
81 ExitWithError(error_fd, "DupDescriptor-dup2");
82
83 ::close(target_fd);
84}
85
86namespace {
87struct ForkFileAction {
88 ForkFileAction(const FileAction &act);
89
90 FileAction::Action action;
91 int fd;
92 std::string path;
93 int arg;
94};
95
96struct ForkLaunchInfo {
97 ForkLaunchInfo(const ProcessLaunchInfo &info, int error_fd);
98
99 bool separate_process_group;
100 bool debug;
101 bool disable_aslr;
102 std::string wd;
103 std::string executable;
104 const char **argv;
105 Environment::Envp envp;
106 std::vector<ForkFileAction> actions;
107 std::vector<int> preserved_fds;
108
109 bool keep_fd(int fd) const {
110 return std::binary_search(preserved_fds.begin(), preserved_fds.end(), fd);
111 }
112};
113} // namespace
114
115static void CloseFileDescriptors(const ForkLaunchInfo &info) {
116#if defined(__FreeBSD__) && __FreeBSD_version >= 1202000
117 // Close gaps between preserved descriptors without scanning RLIMIT_NOFILE.
118 // The list is prepared before fork, so this path needs no allocations.
119 unsigned first = 0;
120 bool closed = true;
121 for (int fd : info.preserved_fds) {
122 if (first < static_cast<unsigned>(fd) &&
123 close_range(first, fd - 1, 0) != 0) {
124 closed = false;
125 break;
126 }
127 first = static_cast<unsigned>(fd) + 1;
128 }
129 if (closed && close_range(first, UINT_MAX, 0) == 0)
130 return;
131 // An older running kernel may not implement close_range. Fall back to the
132 // existing cleanup, including when some ranges have already been closed.
133#endif
134
135 // NB: This fallback is not async-signal safe, but we currently do not launch
136 // processes for debugging from within multithreaded contexts.
137 const llvm::StringRef proc_fd_path = "/proc/self/fd";
138 std::error_code ec;
139 bool result = false;
140 ec = llvm::sys::fs::is_directory(proc_fd_path, result);
141 if (result) {
142 std::vector<int> files_to_close;
143 // Directory iterator doesn't ensure any sequence.
144 for (llvm::sys::fs::directory_iterator iter(proc_fd_path, ec), file_end;
145 iter != file_end && !ec; iter.increment(ec)) {
146 int fd = std::stoi(iter->path().substr(proc_fd_path.size() + 1));
147
148 if (!info.keep_fd(fd))
149 files_to_close.push_back(fd);
150 }
151 for (int file_to_close : files_to_close)
152 close(file_to_close);
153 } else {
154 // Since /proc/self/fd didn't work, trying the slow way instead.
155 int max_fd = sysconf(_SC_OPEN_MAX);
156 for (int fd = 0; fd < max_fd; ++fd)
157 if (!info.keep_fd(fd))
158 close(fd);
159 }
160}
161
162[[noreturn]] static void ChildFunc(int error_fd, const ForkLaunchInfo &info) {
163 if (info.separate_process_group) {
164 if (setpgid(0, 0) != 0)
165 ExitWithError(error_fd, "setpgid");
166 }
167
168 for (const ForkFileAction &action : info.actions) {
169 switch (action.action) {
171 if (close(action.fd) != 0)
172 ExitWithError(error_fd, "close");
173 break;
175 if (action.fd != action.arg) {
176 if (dup2(action.fd, action.arg) == -1)
177 ExitWithError(error_fd, "dup2");
178 } else {
179 if (fcntl(action.fd, F_SETFD,
180 fcntl(action.fd, F_GETFD) & ~FD_CLOEXEC) == -1)
181 ExitWithError(error_fd, "fcntl");
182 }
183 break;
185 DupDescriptor(error_fd, action.path.c_str(), action.fd, action.arg);
186 break;
188 break;
189 }
190 }
191
192 // Change working directory
193 if (!info.wd.empty() && 0 != ::chdir(info.wd.c_str()))
194 ExitWithError(error_fd, "chdir");
195
196 if (info.disable_aslr)
197 DisableASLR(error_fd);
198
199 // Clear the signal mask to prevent the child from being affected by any
200 // masking done by the parent.
201 sigset_t set;
202 if (sigemptyset(&set) != 0 ||
203 pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
204 ExitWithError(error_fd, "pthread_sigmask");
205
206 if (info.debug) {
207 // Do not inherit setgid powers.
208 if (setgid(getgid()) != 0)
209 ExitWithError(error_fd, "setgid");
210
211 // HACK:
212 // Close everything besides stdin, stdout, and stderr that has no file
213 // action to avoid leaking. Only do this when debugging, as elsewhere we
214 // actually rely on passing open descriptors to child processes.
216
217 // Start tracing this child that is about to exec.
218#ifdef _AIX
219 if (ptrace64(PT_TRACE_ME, 0, 0, 0, nullptr) == -1)
220#else
221 if (ptrace(PT_TRACE_ME, 0, nullptr, 0) == -1)
222#endif
223 ExitWithError(error_fd, "ptrace");
224 }
225
226 // Execute. We should never return...
227 execve(info.executable.c_str(), const_cast<char *const *>(info.argv),
228 info.envp);
229
230#if defined(__linux__)
231 if (errno == ETXTBSY) {
232 // On android M and earlier we can get this error because the adb daemon
233 // can hold a write handle on the executable even after it has finished
234 // uploading it. This state lasts only a short time and happens only when
235 // there are many concurrent adb commands being issued, such as when
236 // running the test suite. (The file remains open when someone does an "adb
237 // shell" command in the fork() child before it has had a chance to exec.)
238 // Since this state should clear up quickly, wait a while and then give it
239 // one more go.
240 usleep(50000);
241 execve(info.executable.c_str(), const_cast<char *const *>(info.argv),
242 info.envp);
243 }
244#endif
245
246 // ...unless exec fails. In which case we definitely need to end the child
247 // here.
248 ExitWithError(error_fd, "execve");
249}
250
251// End of code running in the child process.
252
253ForkFileAction::ForkFileAction(const FileAction &act)
254 : action(act.GetAction()), fd(act.GetFD()),
255 path(act.GetFileSpec().GetPath()), arg(act.GetActionArgument()) {}
256
257static std::vector<ForkFileAction>
259 std::vector<ForkFileAction> result;
260 for (size_t i = 0; i < info.GetNumFileActions(); ++i)
261 result.emplace_back(*info.GetFileActionAtIndex(i));
262 return result;
263}
264
265ForkLaunchInfo::ForkLaunchInfo(const ProcessLaunchInfo &info, int error_fd)
266 : separate_process_group(
267 info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)),
268 debug(info.GetFlags().Test(eLaunchFlagDebug)),
269 disable_aslr(info.GetFlags().Test(eLaunchFlagDisableASLR)),
270 wd(info.GetWorkingDirectory().GetPath()),
271 executable(info.GetExecutableFile().GetPath()),
272 argv(info.GetArguments().GetConstArgumentVector()),
273 envp(info.GetEnvironment().getEnvp()), actions(MakeForkActions(info)) {
274 // The child only uses this list when it launches under debugger tracing.
275 if (!debug)
276 return;
277
278 preserved_fds = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
279 auto preserve = [&](int fd) {
280 if (fd >= 0)
281 preserved_fds.push_back(fd);
282 };
283 preserve(error_fd);
284 for (const ForkFileAction &action : actions) {
285 preserve(action.fd);
286 if (action.action == FileAction::eFileActionDuplicate)
287 preserve(action.arg);
288 }
289 std::sort(preserved_fds.begin(), preserved_fds.end());
290 preserved_fds.erase(std::unique(preserved_fds.begin(), preserved_fds.end()),
291 preserved_fds.end());
292}
293
296 Status &error) {
297 // A pipe used by the child process to report errors.
298 PipePosix pipe;
299 error = pipe.CreateNew();
300 if (error.Fail())
301 return HostProcess();
302
303 const ForkLaunchInfo fork_launch_info(launch_info,
305
306 ::pid_t pid = ::fork();
307 if (pid == -1) {
308 // Fork failed
310 "Fork failed with error message: {0}", llvm::sys::StrError());
312 }
313 if (pid == 0) {
314 // child process
316 ChildFunc(pipe.ReleaseWriteFileDescriptor(), fork_launch_info);
317 }
318
319 // parent process
320
322 llvm::SmallString<0> buf;
323 size_t pos = 0;
324 ssize_t r = 0;
325 do {
326 pos += r;
327 buf.resize_for_overwrite(pos + 100);
328 r = llvm::sys::RetryAfterSignal(-1, read, pipe.GetReadFileDescriptor(),
329 buf.begin() + pos, buf.size() - pos);
330 } while (r > 0);
331 assert(r != -1);
332
333 buf.resize(pos);
334 if (buf.empty())
335 return HostProcess(pid); // No error. We're done.
336
337 error = Status(buf.str().str());
338
339 llvm::sys::RetryAfterSignal(-1, waitpid, pid, nullptr, 0);
340
341 return HostProcess();
342}
static llvm::raw_ostream & error(Stream &strm)
static void ExitWithError(int error_fd, const char *operation)
static void DisableASLR(int error_fd)
static std::vector< ForkFileAction > MakeForkActions(const ProcessLaunchInfo &info)
static void DupDescriptor(int error_fd, const char *file, int fd, int flags)
static void write_string(int error_fd, const char *str)
static void ChildFunc(int error_fd, const ForkLaunchInfo &info)
static void CloseFileDescriptors(const ForkLaunchInfo &info)
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
A posix-based implementation of Pipe, a class that abtracts unix style pipes.
Definition PipePosix.h:22
int GetReadFileDescriptor() const override
void CloseWriteFileDescriptor() override
Status CreateNew() override
Definition PipePosix.cpp:82
int ReleaseWriteFileDescriptor() override
void CloseReadFileDescriptor() override
int GetWriteFileDescriptor() const override
const FileAction * GetFileActionAtIndex(size_t idx) const
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
An error handling class.
Definition Status.h:118
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
#define LLDB_INVALID_PROCESS_ID
A class that represents a running process on the host machine.
uint64_t pid_t
Definition lldb-types.h:84
pid_t fork(void)