1 //===-- ProcessLaunchInfo.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 <climits>
11
12 #include "lldb/Host/Config.h"
13 #include "lldb/Host/FileSystem.h"
14 #include "lldb/Host/HostInfo.h"
15 #include "lldb/Target/FileAction.h"
16 #include "lldb/Target/ProcessLaunchInfo.h"
17 #include "lldb/Utility/Log.h"
18 #include "lldb/Utility/StreamString.h"
19
20 #include "llvm/Support/ConvertUTF.h"
21 #include "llvm/Support/FileSystem.h"
22
23 #if !defined(_WIN32)
24 #include <limits.h>
25 #endif
26
27 using namespace lldb;
28 using namespace lldb_private;
29
30 //----------------------------------------------------------------------------
31 // ProcessLaunchInfo member functions
32 //----------------------------------------------------------------------------
33
ProcessLaunchInfo()34 ProcessLaunchInfo::ProcessLaunchInfo()
35 : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(0),
36 m_file_actions(), m_pty(new PseudoTerminal), m_resume_count(0),
37 m_monitor_callback(nullptr), m_monitor_callback_baton(nullptr),
38 m_monitor_signals(false), m_listener_sp(), m_hijack_listener_sp() {}
39
ProcessLaunchInfo(const FileSpec & stdin_file_spec,const FileSpec & stdout_file_spec,const FileSpec & stderr_file_spec,const FileSpec & working_directory,uint32_t launch_flags)40 ProcessLaunchInfo::ProcessLaunchInfo(const FileSpec &stdin_file_spec,
41 const FileSpec &stdout_file_spec,
42 const FileSpec &stderr_file_spec,
43 const FileSpec &working_directory,
44 uint32_t launch_flags)
45 : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
46 m_file_actions(), m_pty(new PseudoTerminal), m_resume_count(0),
47 m_monitor_callback(nullptr), m_monitor_callback_baton(nullptr),
48 m_monitor_signals(false), m_listener_sp(), m_hijack_listener_sp() {
49 if (stdin_file_spec) {
50 FileAction file_action;
51 const bool read = true;
52 const bool write = false;
53 if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
54 AppendFileAction(file_action);
55 }
56 if (stdout_file_spec) {
57 FileAction file_action;
58 const bool read = false;
59 const bool write = true;
60 if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
61 AppendFileAction(file_action);
62 }
63 if (stderr_file_spec) {
64 FileAction file_action;
65 const bool read = false;
66 const bool write = true;
67 if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
68 AppendFileAction(file_action);
69 }
70 if (working_directory)
71 SetWorkingDirectory(working_directory);
72 }
73
AppendCloseFileAction(int fd)74 bool ProcessLaunchInfo::AppendCloseFileAction(int fd) {
75 FileAction file_action;
76 if (file_action.Close(fd)) {
77 AppendFileAction(file_action);
78 return true;
79 }
80 return false;
81 }
82
AppendDuplicateFileAction(int fd,int dup_fd)83 bool ProcessLaunchInfo::AppendDuplicateFileAction(int fd, int dup_fd) {
84 FileAction file_action;
85 if (file_action.Duplicate(fd, dup_fd)) {
86 AppendFileAction(file_action);
87 return true;
88 }
89 return false;
90 }
91
AppendOpenFileAction(int fd,const FileSpec & file_spec,bool read,bool write)92 bool ProcessLaunchInfo::AppendOpenFileAction(int fd, const FileSpec &file_spec,
93 bool read, bool write) {
94 FileAction file_action;
95 if (file_action.Open(fd, file_spec, read, write)) {
96 AppendFileAction(file_action);
97 return true;
98 }
99 return false;
100 }
101
AppendSuppressFileAction(int fd,bool read,bool write)102 bool ProcessLaunchInfo::AppendSuppressFileAction(int fd, bool read,
103 bool write) {
104 FileAction file_action;
105 if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
106 AppendFileAction(file_action);
107 return true;
108 }
109 return false;
110 }
111
GetFileActionAtIndex(size_t idx) const112 const FileAction *ProcessLaunchInfo::GetFileActionAtIndex(size_t idx) const {
113 if (idx < m_file_actions.size())
114 return &m_file_actions[idx];
115 return nullptr;
116 }
117
GetFileActionForFD(int fd) const118 const FileAction *ProcessLaunchInfo::GetFileActionForFD(int fd) const {
119 for (size_t idx = 0, count = m_file_actions.size(); idx < count; ++idx) {
120 if (m_file_actions[idx].GetFD() == fd)
121 return &m_file_actions[idx];
122 }
123 return nullptr;
124 }
125
GetWorkingDirectory() const126 const FileSpec &ProcessLaunchInfo::GetWorkingDirectory() const {
127 return m_working_dir;
128 }
129
SetWorkingDirectory(const FileSpec & working_dir)130 void ProcessLaunchInfo::SetWorkingDirectory(const FileSpec &working_dir) {
131 m_working_dir = working_dir;
132 }
133
GetProcessPluginName() const134 const char *ProcessLaunchInfo::GetProcessPluginName() const {
135 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
136 }
137
SetProcessPluginName(llvm::StringRef plugin)138 void ProcessLaunchInfo::SetProcessPluginName(llvm::StringRef plugin) {
139 m_plugin_name = plugin;
140 }
141
GetShell() const142 const FileSpec &ProcessLaunchInfo::GetShell() const { return m_shell; }
143
SetShell(const FileSpec & shell)144 void ProcessLaunchInfo::SetShell(const FileSpec &shell) {
145 m_shell = shell;
146 if (m_shell) {
147 FileSystem::Instance().ResolveExecutableLocation(m_shell);
148 m_flags.Set(lldb::eLaunchFlagLaunchInShell);
149 } else
150 m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
151 }
152
SetLaunchInSeparateProcessGroup(bool separate)153 void ProcessLaunchInfo::SetLaunchInSeparateProcessGroup(bool separate) {
154 if (separate)
155 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
156 else
157 m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
158 }
159
SetShellExpandArguments(bool expand)160 void ProcessLaunchInfo::SetShellExpandArguments(bool expand) {
161 if (expand)
162 m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
163 else
164 m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
165 }
166
Clear()167 void ProcessLaunchInfo::Clear() {
168 ProcessInfo::Clear();
169 m_working_dir.Clear();
170 m_plugin_name.clear();
171 m_shell.Clear();
172 m_flags.Clear();
173 m_file_actions.clear();
174 m_resume_count = 0;
175 m_listener_sp.reset();
176 m_hijack_listener_sp.reset();
177 }
178
SetMonitorProcessCallback(const Host::MonitorChildProcessCallback & callback,bool monitor_signals)179 void ProcessLaunchInfo::SetMonitorProcessCallback(
180 const Host::MonitorChildProcessCallback &callback, bool monitor_signals) {
181 m_monitor_callback = callback;
182 m_monitor_signals = monitor_signals;
183 }
184
NoOpMonitorCallback(lldb::pid_t pid,bool exited,int signal,int status)185 bool ProcessLaunchInfo::NoOpMonitorCallback(lldb::pid_t pid, bool exited, int signal, int status) {
186 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
187 LLDB_LOG(log, "pid = {0}, exited = {1}, signal = {2}, status = {3}", pid,
188 exited, signal, status);
189 return true;
190 }
191
MonitorProcess() const192 bool ProcessLaunchInfo::MonitorProcess() const {
193 if (m_monitor_callback && ProcessIDIsValid()) {
194 Host::StartMonitoringChildProcess(m_monitor_callback, GetProcessID(),
195 m_monitor_signals);
196 return true;
197 }
198 return false;
199 }
200
SetDetachOnError(bool enable)201 void ProcessLaunchInfo::SetDetachOnError(bool enable) {
202 if (enable)
203 m_flags.Set(lldb::eLaunchFlagDetachOnError);
204 else
205 m_flags.Clear(lldb::eLaunchFlagDetachOnError);
206 }
207
SetUpPtyRedirection()208 llvm::Error ProcessLaunchInfo::SetUpPtyRedirection() {
209 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
210 LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
211
212 int open_flags = O_RDWR | O_NOCTTY;
213 #if !defined(_WIN32)
214 // We really shouldn't be specifying platform specific flags that are
215 // intended for a system call in generic code. But this will have to
216 // do for now.
217 open_flags |= O_CLOEXEC;
218 #endif
219 if (!m_pty->OpenFirstAvailableMaster(open_flags, nullptr, 0)) {
220 return llvm::createStringError(llvm::inconvertibleErrorCode(),
221 "PTY::OpenFirstAvailableMaster failed");
222 }
223 const FileSpec slave_file_spec(m_pty->GetSlaveName(nullptr, 0));
224
225 // Only use the slave tty if we don't have anything specified for
226 // input and don't have an action for stdin
227 if (GetFileActionForFD(STDIN_FILENO) == nullptr)
228 AppendOpenFileAction(STDIN_FILENO, slave_file_spec, true, false);
229
230 // Only use the slave tty if we don't have anything specified for
231 // output and don't have an action for stdout
232 if (GetFileActionForFD(STDOUT_FILENO) == nullptr)
233 AppendOpenFileAction(STDOUT_FILENO, slave_file_spec, false, true);
234
235 // Only use the slave tty if we don't have anything specified for
236 // error and don't have an action for stderr
237 if (GetFileActionForFD(STDERR_FILENO) == nullptr)
238 AppendOpenFileAction(STDERR_FILENO, slave_file_spec, false, true);
239 return llvm::Error::success();
240 }
241
ConvertArgumentsForLaunchingInShell(Status & error,bool localhost,bool will_debug,bool first_arg_is_full_shell_command,int32_t num_resumes)242 bool ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell(
243 Status &error, bool localhost, bool will_debug,
244 bool first_arg_is_full_shell_command, int32_t num_resumes) {
245 error.Clear();
246
247 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
248 if (m_shell) {
249 std::string shell_executable = m_shell.GetPath();
250
251 const char **argv = GetArguments().GetConstArgumentVector();
252 if (argv == nullptr || argv[0] == nullptr)
253 return false;
254 Args shell_arguments;
255 std::string safe_arg;
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 const char *arg =
333 Args::GetShellSafeArgument(m_shell, argv[i], safe_arg);
334 shell_command.Printf(" %s", arg);
335 }
336 }
337 shell_arguments.AppendArgument(shell_command.GetString());
338 m_executable = m_shell;
339 m_arguments = shell_arguments;
340 return true;
341 } else {
342 error.SetErrorString("invalid shell path");
343 }
344 } else {
345 error.SetErrorString("not launching in shell");
346 }
347 return false;
348 }
349