1 //===-- ProcessLauncherLinux.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 "lldb/Host/posix/ProcessLauncherPosixFork.h"
11 #include "lldb/Host/Host.h"
12 #include "lldb/Host/HostProcess.h"
13 #include "lldb/Host/Pipe.h"
14 #include "lldb/Target/ProcessLaunchInfo.h"
15 #include "lldb/Utility/FileSpec.h"
16 #include "lldb/Utility/Log.h"
17 #include "llvm/Support/Errno.h"
18 
19 #include <limits.h>
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(Args &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   static const char *path = "PATH=";
47   for (auto &entry : env.entries()) {
48     if (entry.ref.startswith(path))
49       return;
50   }
51   env.AppendArgument(llvm::StringRef("PATH=/system/bin"));
52 #endif
53 }
54 
55 static void LLVM_ATTRIBUTE_NORETURN ExitWithError(int error_fd,
56                                                   const char *operation) {
57   int err = errno;
58   llvm::raw_fd_ostream os(error_fd, true);
59   os << operation << " failed: " << llvm::sys::StrError(err);
60   os.flush();
61   _exit(1);
62 }
63 
64 static void DisableASLRIfRequested(int error_fd, const ProcessLaunchInfo &info) {
65 #if defined(__linux__)
66   if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) {
67     const unsigned long personality_get_current = 0xffffffff;
68     int value = personality(personality_get_current);
69     if (value == -1)
70       ExitWithError(error_fd, "personality get");
71 
72     value = personality(ADDR_NO_RANDOMIZE | value);
73     if (value == -1)
74       ExitWithError(error_fd, "personality set");
75   }
76 #endif
77 }
78 
79 static void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd,
80                           int flags) {
81   int target_fd = ::open(file_spec.GetCString(), flags, 0666);
82 
83   if (target_fd == -1)
84     ExitWithError(error_fd, "DupDescriptor-open");
85 
86   if (target_fd == fd)
87     return;
88 
89   if (::dup2(target_fd, fd) == -1)
90     ExitWithError(error_fd, "DupDescriptor-dup2");
91 
92   ::close(target_fd);
93   return;
94 }
95 
96 static void LLVM_ATTRIBUTE_NORETURN ChildFunc(int error_fd,
97                                               const ProcessLaunchInfo &info) {
98   // Do not inherit setgid powers.
99   if (setgid(getgid()) != 0)
100     ExitWithError(error_fd, "setgid");
101 
102   if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) {
103     if (setpgid(0, 0) != 0)
104       ExitWithError(error_fd, "setpgid");
105   }
106 
107   for (size_t i = 0; i < info.GetNumFileActions(); ++i) {
108     const FileAction &action = *info.GetFileActionAtIndex(i);
109     switch (action.GetAction()) {
110     case FileAction::eFileActionClose:
111       if (close(action.GetFD()) != 0)
112         ExitWithError(error_fd, "close");
113       break;
114     case FileAction::eFileActionDuplicate:
115       if (dup2(action.GetFD(), action.GetActionArgument()) == -1)
116         ExitWithError(error_fd, "dup2");
117       break;
118     case FileAction::eFileActionOpen:
119       DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(),
120                     action.GetActionArgument());
121       break;
122     case FileAction::eFileActionNone:
123       break;
124     }
125   }
126 
127   const char **argv = info.GetArguments().GetConstArgumentVector();
128 
129   // Change working directory
130   if (info.GetWorkingDirectory() &&
131       0 != ::chdir(info.GetWorkingDirectory().GetCString()))
132     ExitWithError(error_fd, "chdir");
133 
134   DisableASLRIfRequested(error_fd, info);
135   Args env = info.GetEnvironmentEntries();
136   FixupEnvironment(env);
137   const char **envp = env.GetConstArgumentVector();
138 
139   // Clear the signal mask to prevent the child from being affected by
140   // any masking done by the parent.
141   sigset_t set;
142   if (sigemptyset(&set) != 0 ||
143       pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
144     ExitWithError(error_fd, "pthread_sigmask");
145 
146   if (info.GetFlags().Test(eLaunchFlagDebug)) {
147     // HACK:
148     // Close everything besides stdin, stdout, and stderr that has no file
149     // action to avoid leaking. Only do this when debugging, as elsewhere we
150     // actually rely on
151     // passing open descriptors to child processes.
152     for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
153       if (!info.GetFileActionForFD(fd) && fd != error_fd)
154         close(fd);
155 
156     // Start tracing this child that is about to exec.
157     if (ptrace(PT_TRACE_ME, 0, nullptr, 0) == -1)
158       ExitWithError(error_fd, "ptrace");
159   }
160 
161   // Execute.  We should never return...
162   execve(argv[0], const_cast<char *const *>(argv),
163          const_cast<char *const *>(envp));
164 
165 #if defined(__linux__)
166   if (errno == ETXTBSY) {
167     // On android M and earlier we can get this error because the adb deamon can
168     // hold a write
169     // handle on the executable even after it has finished uploading it. This
170     // state lasts
171     // only a short time and happens only when there are many concurrent adb
172     // commands being
173     // issued, such as when running the test suite. (The file remains open when
174     // someone does
175     // an "adb shell" command in the fork() child before it has had a chance to
176     // exec.) Since
177     // this state should clear up quickly, wait a while and then give it one
178     // more go.
179     usleep(50000);
180     execve(argv[0], const_cast<char *const *>(argv),
181            const_cast<char *const *>(envp));
182   }
183 #endif
184 
185   // ...unless exec fails.  In which case we definitely need to end the child
186   // here.
187   ExitWithError(error_fd, "execve");
188 }
189 
190 HostProcess
191 ProcessLauncherPosixFork::LaunchProcess(const ProcessLaunchInfo &launch_info,
192                                         Status &error) {
193   char exe_path[PATH_MAX];
194   launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path));
195 
196   // A pipe used by the child process to report errors.
197   PipePosix pipe;
198   const bool child_processes_inherit = false;
199   error = pipe.CreateNew(child_processes_inherit);
200   if (error.Fail())
201     return HostProcess();
202 
203   ::pid_t pid = ::fork();
204   if (pid == -1) {
205     // Fork failed
206     error.SetErrorStringWithFormatv("Fork failed with error message: {0}",
207                                     llvm::sys::StrError());
208     return HostProcess(LLDB_INVALID_PROCESS_ID);
209   }
210   if (pid == 0) {
211     // child process
212     pipe.CloseReadFileDescriptor();
213     ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info);
214   }
215 
216   // parent process
217 
218   pipe.CloseWriteFileDescriptor();
219   char buf[1000];
220   int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf);
221 
222   if (r == 0)
223     return HostProcess(pid); // No error. We're done.
224 
225   error.SetErrorString(buf);
226 
227   waitpid(pid, nullptr, 0);
228 
229   return HostProcess();
230 }
231