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