1 //===-- ProcessLaunchInfo.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 <climits>
10 
11 #include "lldb/Host/Config.h"
12 #include "lldb/Host/FileAction.h"
13 #include "lldb/Host/FileSystem.h"
14 #include "lldb/Host/HostInfo.h"
15 #include "lldb/Host/ProcessLaunchInfo.h"
16 #include "lldb/Utility/Log.h"
17 #include "lldb/Utility/StreamString.h"
18 
19 #include "llvm/Support/ConvertUTF.h"
20 #include "llvm/Support/FileSystem.h"
21 
22 #if !defined(_WIN32)
23 #include <limits.h>
24 #endif
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 // ProcessLaunchInfo member functions
30 
ProcessLaunchInfo()31 ProcessLaunchInfo::ProcessLaunchInfo()
32     : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(0),
33       m_file_actions(), m_pty(new PseudoTerminal), m_resume_count(0),
34       m_monitor_callback(nullptr), m_monitor_callback_baton(nullptr),
35       m_monitor_signals(false), m_listener_sp(), m_hijack_listener_sp() {}
36 
ProcessLaunchInfo(const FileSpec & stdin_file_spec,const FileSpec & stdout_file_spec,const FileSpec & stderr_file_spec,const FileSpec & working_directory,uint32_t launch_flags)37 ProcessLaunchInfo::ProcessLaunchInfo(const FileSpec &stdin_file_spec,
38                                      const FileSpec &stdout_file_spec,
39                                      const FileSpec &stderr_file_spec,
40                                      const FileSpec &working_directory,
41                                      uint32_t launch_flags)
42     : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
43       m_file_actions(), m_pty(new PseudoTerminal), m_resume_count(0),
44       m_monitor_callback(nullptr), m_monitor_callback_baton(nullptr),
45       m_monitor_signals(false), m_listener_sp(), m_hijack_listener_sp() {
46   if (stdin_file_spec) {
47     FileAction file_action;
48     const bool read = true;
49     const bool write = false;
50     if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
51       AppendFileAction(file_action);
52   }
53   if (stdout_file_spec) {
54     FileAction file_action;
55     const bool read = false;
56     const bool write = true;
57     if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
58       AppendFileAction(file_action);
59   }
60   if (stderr_file_spec) {
61     FileAction file_action;
62     const bool read = false;
63     const bool write = true;
64     if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
65       AppendFileAction(file_action);
66   }
67   if (working_directory)
68     SetWorkingDirectory(working_directory);
69 }
70 
AppendCloseFileAction(int fd)71 bool ProcessLaunchInfo::AppendCloseFileAction(int fd) {
72   FileAction file_action;
73   if (file_action.Close(fd)) {
74     AppendFileAction(file_action);
75     return true;
76   }
77   return false;
78 }
79 
AppendDuplicateFileAction(int fd,int dup_fd)80 bool ProcessLaunchInfo::AppendDuplicateFileAction(int fd, int dup_fd) {
81   FileAction file_action;
82   if (file_action.Duplicate(fd, dup_fd)) {
83     AppendFileAction(file_action);
84     return true;
85   }
86   return false;
87 }
88 
AppendOpenFileAction(int fd,const FileSpec & file_spec,bool read,bool write)89 bool ProcessLaunchInfo::AppendOpenFileAction(int fd, const FileSpec &file_spec,
90                                              bool read, bool write) {
91   FileAction file_action;
92   if (file_action.Open(fd, file_spec, read, write)) {
93     AppendFileAction(file_action);
94     return true;
95   }
96   return false;
97 }
98 
AppendSuppressFileAction(int fd,bool read,bool write)99 bool ProcessLaunchInfo::AppendSuppressFileAction(int fd, bool read,
100                                                  bool write) {
101   FileAction file_action;
102   if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
103     AppendFileAction(file_action);
104     return true;
105   }
106   return false;
107 }
108 
GetFileActionAtIndex(size_t idx) const109 const FileAction *ProcessLaunchInfo::GetFileActionAtIndex(size_t idx) const {
110   if (idx < m_file_actions.size())
111     return &m_file_actions[idx];
112   return nullptr;
113 }
114 
GetFileActionForFD(int fd) const115 const FileAction *ProcessLaunchInfo::GetFileActionForFD(int fd) const {
116   for (size_t idx = 0, count = m_file_actions.size(); idx < count; ++idx) {
117     if (m_file_actions[idx].GetFD() == fd)
118       return &m_file_actions[idx];
119   }
120   return nullptr;
121 }
122 
GetWorkingDirectory() const123 const FileSpec &ProcessLaunchInfo::GetWorkingDirectory() const {
124   return m_working_dir;
125 }
126 
SetWorkingDirectory(const FileSpec & working_dir)127 void ProcessLaunchInfo::SetWorkingDirectory(const FileSpec &working_dir) {
128   m_working_dir = working_dir;
129 }
130 
GetProcessPluginName() const131 const char *ProcessLaunchInfo::GetProcessPluginName() const {
132   return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
133 }
134 
SetProcessPluginName(llvm::StringRef plugin)135 void ProcessLaunchInfo::SetProcessPluginName(llvm::StringRef plugin) {
136   m_plugin_name = std::string(plugin);
137 }
138 
GetShell() const139 const FileSpec &ProcessLaunchInfo::GetShell() const { return m_shell; }
140 
SetShell(const FileSpec & shell)141 void ProcessLaunchInfo::SetShell(const FileSpec &shell) {
142   m_shell = shell;
143   if (m_shell) {
144     FileSystem::Instance().ResolveExecutableLocation(m_shell);
145     m_flags.Set(lldb::eLaunchFlagLaunchInShell);
146   } else
147     m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
148 }
149 
SetLaunchInSeparateProcessGroup(bool separate)150 void ProcessLaunchInfo::SetLaunchInSeparateProcessGroup(bool separate) {
151   if (separate)
152     m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
153   else
154     m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
155 }
156 
SetShellExpandArguments(bool expand)157 void ProcessLaunchInfo::SetShellExpandArguments(bool expand) {
158   if (expand)
159     m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
160   else
161     m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
162 }
163 
Clear()164 void ProcessLaunchInfo::Clear() {
165   ProcessInfo::Clear();
166   m_working_dir.Clear();
167   m_plugin_name.clear();
168   m_shell.Clear();
169   m_flags.Clear();
170   m_file_actions.clear();
171   m_resume_count = 0;
172   m_listener_sp.reset();
173   m_hijack_listener_sp.reset();
174 }
175 
SetMonitorProcessCallback(const Host::MonitorChildProcessCallback & callback,bool monitor_signals)176 void ProcessLaunchInfo::SetMonitorProcessCallback(
177     const Host::MonitorChildProcessCallback &callback, bool monitor_signals) {
178   m_monitor_callback = callback;
179   m_monitor_signals = monitor_signals;
180 }
181 
NoOpMonitorCallback(lldb::pid_t pid,bool exited,int signal,int status)182 bool ProcessLaunchInfo::NoOpMonitorCallback(lldb::pid_t pid, bool exited, int signal, int status) {
183   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
184   LLDB_LOG(log, "pid = {0}, exited = {1}, signal = {2}, status = {3}", pid,
185            exited, signal, status);
186   return true;
187 }
188 
MonitorProcess() const189 bool ProcessLaunchInfo::MonitorProcess() const {
190   if (m_monitor_callback && ProcessIDIsValid()) {
191     llvm::Expected<HostThread> maybe_thread =
192     Host::StartMonitoringChildProcess(m_monitor_callback, GetProcessID(),
193                                       m_monitor_signals);
194     if (!maybe_thread)
195       LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
196                "failed to launch host thread: {}",
197                llvm::toString(maybe_thread.takeError()));
198     return true;
199   }
200   return false;
201 }
202 
SetDetachOnError(bool enable)203 void ProcessLaunchInfo::SetDetachOnError(bool enable) {
204   if (enable)
205     m_flags.Set(lldb::eLaunchFlagDetachOnError);
206   else
207     m_flags.Clear(lldb::eLaunchFlagDetachOnError);
208 }
209 
SetUpPtyRedirection()210 llvm::Error ProcessLaunchInfo::SetUpPtyRedirection() {
211   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
212   LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
213 
214   int open_flags = O_RDWR | O_NOCTTY;
215 #if !defined(_WIN32)
216   // We really shouldn't be specifying platform specific flags that are
217   // intended for a system call in generic code.  But this will have to
218   // do for now.
219   open_flags |= O_CLOEXEC;
220 #endif
221   if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
222     return Err;
223 
224   const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
225 
226   // Only use the secondary tty if we don't have anything specified for
227   // input and don't have an action for stdin
228   if (GetFileActionForFD(STDIN_FILENO) == nullptr)
229     AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
230 
231   // Only use the secondary tty if we don't have anything specified for
232   // output and don't have an action for stdout
233   if (GetFileActionForFD(STDOUT_FILENO) == nullptr)
234     AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
235 
236   // Only use the secondary tty if we don't have anything specified for
237   // error and don't have an action for stderr
238   if (GetFileActionForFD(STDERR_FILENO) == nullptr)
239     AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
240   return llvm::Error::success();
241 }
242 
ConvertArgumentsForLaunchingInShell(Status & error,bool will_debug,bool first_arg_is_full_shell_command,uint32_t num_resumes)243 bool ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell(
244     Status &error, bool will_debug, bool first_arg_is_full_shell_command,
245     uint32_t num_resumes) {
246   error.Clear();
247 
248   if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
249     if (m_shell) {
250       std::string shell_executable = m_shell.GetPath();
251 
252       const char **argv = GetArguments().GetConstArgumentVector();
253       if (argv == nullptr || argv[0] == nullptr)
254         return false;
255       Args shell_arguments;
256       shell_arguments.AppendArgument(shell_executable);
257       const llvm::Triple &triple = GetArchitecture().GetTriple();
258       if (triple.getOS() == llvm::Triple::Win32 &&
259           !triple.isWindowsCygwinEnvironment())
260         shell_arguments.AppendArgument(llvm::StringRef("/C"));
261       else
262         shell_arguments.AppendArgument(llvm::StringRef("-c"));
263 
264       StreamString shell_command;
265       if (will_debug) {
266         // Add a modified PATH environment variable in case argv[0] is a
267         // relative path.
268         const char *argv0 = argv[0];
269         FileSpec arg_spec(argv0);
270         if (arg_spec.IsRelative()) {
271           // We have a relative path to our executable which may not work if we
272           // just try to run "a.out" (without it being converted to "./a.out")
273           FileSpec working_dir = GetWorkingDirectory();
274           // Be sure to put quotes around PATH's value in case any paths have
275           // spaces...
276           std::string new_path("PATH=\"");
277           const size_t empty_path_len = new_path.size();
278 
279           if (working_dir) {
280             new_path += working_dir.GetPath();
281           } else {
282             llvm::SmallString<64> cwd;
283             if (! llvm::sys::fs::current_path(cwd))
284               new_path += cwd;
285           }
286           std::string curr_path;
287           if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
288             if (new_path.size() > empty_path_len)
289               new_path += ':';
290             new_path += curr_path;
291           }
292           new_path += "\" ";
293           shell_command.PutCString(new_path);
294         }
295 
296         if (triple.getOS() != llvm::Triple::Win32 ||
297             triple.isWindowsCygwinEnvironment())
298           shell_command.PutCString("exec");
299 
300         // Only Apple supports /usr/bin/arch being able to specify the
301         // architecture
302         if (GetArchitecture().IsValid() && // Valid architecture
303             GetArchitecture().GetTriple().getVendor() ==
304                 llvm::Triple::Apple && // Apple only
305             GetArchitecture().GetCore() !=
306                 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
307         {
308           shell_command.Printf(" /usr/bin/arch -arch %s",
309                                GetArchitecture().GetArchitectureName());
310           // Set the resume count to 2:
311           // 1 - stop in shell
312           // 2 - stop in /usr/bin/arch
313           // 3 - then we will stop in our program
314           SetResumeCount(num_resumes + 1);
315         } else {
316           // Set the resume count to 1:
317           // 1 - stop in shell
318           // 2 - then we will stop in our program
319           SetResumeCount(num_resumes);
320         }
321       }
322 
323       if (first_arg_is_full_shell_command) {
324         // There should only be one argument that is the shell command itself
325         // to be used as is
326         if (argv[0] && !argv[1])
327           shell_command.Printf("%s", argv[0]);
328         else
329           return false;
330       } else {
331         for (size_t i = 0; argv[i] != nullptr; ++i) {
332           std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
333           // Add a space to separate this arg from the previous one.
334           shell_command.PutCString(" ");
335           shell_command.PutCString(safe_arg);
336         }
337       }
338       shell_arguments.AppendArgument(shell_command.GetString());
339       m_executable = m_shell;
340       m_arguments = shell_arguments;
341       return true;
342     } else {
343       error.SetErrorString("invalid shell path");
344     }
345   } else {
346     error.SetErrorString("not launching in shell");
347   }
348   return false;
349 }
350