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 
9 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
10 #include "lldb/Host/Host.h"
11 #include "lldb/Host/HostProcess.h"
12 #include "lldb/Host/Pipe.h"
13 #include "lldb/Host/ProcessLaunchInfo.h"
14 #include "lldb/Utility/FileSpec.h"
15 #include "lldb/Utility/Log.h"
16 #include "llvm/Support/Errno.h"
17 #include "llvm/Support/FileSystem.h"
18 
19 #include <climits>
20 #include <sys/ptrace.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23 
24 #include <sstream>
25 #include <csignal>
26 
27 #ifdef __ANDROID__
28 #include <android/api-level.h>
29 #define PT_TRACE_ME PTRACE_TRACEME
30 #endif
31 
32 #if defined(__ANDROID_API__) && __ANDROID_API__ < 15
33 #include <linux/personality.h>
34 #elif defined(__linux__)
35 #include <sys/personality.h>
36 #endif
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 static void FixupEnvironment(Environment &env) {
42 #ifdef __ANDROID__
43   // If there is no PATH variable specified inside the environment then set the
44   // path to /system/bin. It is required because the default path used by
45   // execve() is wrong on android.
46   env.try_emplace("PATH", "/system/bin");
47 #endif
48 }
49 
50 [[noreturn]] static void ExitWithError(int error_fd,
51                                        const char *operation) {
52   int err = errno;
53   llvm::raw_fd_ostream os(error_fd, true);
54   os << operation << " failed: " << llvm::sys::StrError(err);
55   os.flush();
56   _exit(1);
57 }
58 
59 static void DisableASLRIfRequested(int error_fd, const ProcessLaunchInfo &info) {
60 #if defined(__linux__)
61   if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) {
62     const unsigned long personality_get_current = 0xffffffff;
63     int value = personality(personality_get_current);
64     if (value == -1)
65       ExitWithError(error_fd, "personality get");
66 
67     value = personality(ADDR_NO_RANDOMIZE | value);
68     if (value == -1)
69       ExitWithError(error_fd, "personality set");
70   }
71 #endif
72 }
73 
74 static void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd,
75                           int flags) {
76   int target_fd = llvm::sys::RetryAfterSignal(-1, ::open,
77       file_spec.GetCString(), flags, 0666);
78 
79   if (target_fd == -1)
80     ExitWithError(error_fd, "DupDescriptor-open");
81 
82   if (target_fd == fd)
83     return;
84 
85   if (::dup2(target_fd, fd) == -1)
86     ExitWithError(error_fd, "DupDescriptor-dup2");
87 
88   ::close(target_fd);
89 }
90 
91 [[noreturn]] static void ChildFunc(int error_fd,
92                                    const ProcessLaunchInfo &info) {
93   if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) {
94     if (setpgid(0, 0) != 0)
95       ExitWithError(error_fd, "setpgid");
96   }
97 
98   for (size_t i = 0; i < info.GetNumFileActions(); ++i) {
99     const FileAction &action = *info.GetFileActionAtIndex(i);
100     switch (action.GetAction()) {
101     case FileAction::eFileActionClose:
102       if (close(action.GetFD()) != 0)
103         ExitWithError(error_fd, "close");
104       break;
105     case FileAction::eFileActionDuplicate:
106       if (dup2(action.GetFD(), action.GetActionArgument()) == -1)
107         ExitWithError(error_fd, "dup2");
108       break;
109     case FileAction::eFileActionOpen:
110       DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(),
111                     action.GetActionArgument());
112       break;
113     case FileAction::eFileActionNone:
114       break;
115     }
116   }
117 
118   const char **argv = info.GetArguments().GetConstArgumentVector();
119 
120   // Change working directory
121   if (info.GetWorkingDirectory() &&
122       0 != ::chdir(info.GetWorkingDirectory().GetCString()))
123     ExitWithError(error_fd, "chdir");
124 
125   DisableASLRIfRequested(error_fd, info);
126   Environment env = info.GetEnvironment();
127   FixupEnvironment(env);
128   Environment::Envp envp = env.getEnvp();
129 
130   // Clear the signal mask to prevent the child from being affected by any
131   // masking done by the parent.
132   sigset_t set;
133   if (sigemptyset(&set) != 0 ||
134       pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
135     ExitWithError(error_fd, "pthread_sigmask");
136 
137   if (info.GetFlags().Test(eLaunchFlagDebug)) {
138     // Do not inherit setgid powers.
139     if (setgid(getgid()) != 0)
140       ExitWithError(error_fd, "setgid");
141 
142     // HACK:
143     // Close everything besides stdin, stdout, and stderr that has no file
144     // action to avoid leaking. Only do this when debugging, as elsewhere we
145     // actually rely on passing open descriptors to child processes.
146 
147     const llvm::StringRef proc_fd_path = "/proc/self/fd";
148     std::error_code ec;
149     bool result;
150     ec = llvm::sys::fs::is_directory(proc_fd_path, result);
151     if (result) {
152       std::vector<int> files_to_close;
153       // Directory iterator doesn't ensure any sequence.
154       for (llvm::sys::fs::directory_iterator iter(proc_fd_path, ec), file_end;
155            iter != file_end && !ec; iter.increment(ec)) {
156         int fd = std::stoi(iter->path().substr(proc_fd_path.size() + 1));
157 
158         // Don't close first three entries since they are stdin, stdout and
159         // stderr.
160         if (fd > 2 && !info.GetFileActionForFD(fd) && fd != error_fd)
161           files_to_close.push_back(fd);
162       }
163       for (int file_to_close : files_to_close)
164         close(file_to_close);
165     } else {
166       // Since /proc/self/fd didn't work, trying the slow way instead.
167       int max_fd = sysconf(_SC_OPEN_MAX);
168       for (int fd = 3; fd < max_fd; ++fd)
169         if (!info.GetFileActionForFD(fd) && fd != error_fd)
170           close(fd);
171     }
172 
173     // Start tracing this child that is about to exec.
174     if (ptrace(PT_TRACE_ME, 0, nullptr, 0) == -1)
175       ExitWithError(error_fd, "ptrace");
176   }
177 
178   // Execute.  We should never return...
179   execve(argv[0], const_cast<char *const *>(argv), envp);
180 
181 #if defined(__linux__)
182   if (errno == ETXTBSY) {
183     // On android M and earlier we can get this error because the adb daemon
184     // can hold a write handle on the executable even after it has finished
185     // uploading it. This state lasts only a short time and happens only when
186     // there are many concurrent adb commands being issued, such as when
187     // running the test suite. (The file remains open when someone does an "adb
188     // shell" command in the fork() child before it has had a chance to exec.)
189     // Since this state should clear up quickly, wait a while and then give it
190     // one more go.
191     usleep(50000);
192     execve(argv[0], const_cast<char *const *>(argv), envp);
193   }
194 #endif
195 
196   // ...unless exec fails.  In which case we definitely need to end the child
197   // here.
198   ExitWithError(error_fd, "execve");
199 }
200 
201 HostProcess
202 ProcessLauncherPosixFork::LaunchProcess(const ProcessLaunchInfo &launch_info,
203                                         Status &error) {
204   char exe_path[PATH_MAX];
205   launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path));
206 
207   // A pipe used by the child process to report errors.
208   PipePosix pipe;
209   const bool child_processes_inherit = false;
210   error = pipe.CreateNew(child_processes_inherit);
211   if (error.Fail())
212     return HostProcess();
213 
214   ::pid_t pid = ::fork();
215   if (pid == -1) {
216     // Fork failed
217     error.SetErrorStringWithFormatv("Fork failed with error message: {0}",
218                                     llvm::sys::StrError());
219     return HostProcess(LLDB_INVALID_PROCESS_ID);
220   }
221   if (pid == 0) {
222     // child process
223     pipe.CloseReadFileDescriptor();
224     ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info);
225   }
226 
227   // parent process
228 
229   pipe.CloseWriteFileDescriptor();
230   char buf[1000];
231   int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf);
232 
233   if (r == 0)
234     return HostProcess(pid); // No error. We're done.
235 
236   error.SetErrorString(buf);
237 
238   llvm::sys::RetryAfterSignal(-1, waitpid, pid, nullptr, 0);
239 
240   return HostProcess();
241 }
242