LLDB mainline
ProcessLaunchInfo.cpp
Go to the documentation of this file.
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"
14#include "lldb/Host/HostInfo.h"
17#include "lldb/Utility/Log.h"
19
20#include "llvm/Support/ConvertUTF.h"
21#include "llvm/Support/FileSystem.h"
22
23#ifdef _WIN32
25#else
26#include <climits>
27#endif
28
29using namespace lldb;
30using namespace lldb_private;
31
32// ProcessLaunchInfo member functions
33
37
39 const FileSpec &stdout_file_spec,
40 const FileSpec &stderr_file_spec,
41 const FileSpec &working_directory,
42 uint32_t launch_flags)
43 : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
44 m_file_actions(), m_pty(new PTY) {
45 if (stdin_file_spec) {
46 FileAction file_action;
47 const bool read = true;
48 const bool write = false;
49 if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
50 AppendFileAction(file_action);
51 }
52 if (stdout_file_spec) {
53 FileAction file_action;
54 const bool read = false;
55 const bool write = true;
56 if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
57 AppendFileAction(file_action);
58 }
59 if (stderr_file_spec) {
60 FileAction file_action;
61 const bool read = false;
62 const bool write = true;
63 if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
64 AppendFileAction(file_action);
65 }
66 if (working_directory)
67 SetWorkingDirectory(working_directory);
68}
69
71 FileAction file_action;
72 if (file_action.Close(fd)) {
73 AppendFileAction(file_action);
74 return true;
75 }
76 return false;
77}
78
80 FileAction file_action;
81 if (file_action.Duplicate(fd, dup_fd)) {
82 AppendFileAction(file_action);
83 return true;
84 }
85 return false;
86}
87
89 bool read, bool write) {
90 FileAction file_action;
91 if (file_action.Open(fd, file_spec, read, write)) {
92 AppendFileAction(file_action);
93 return true;
94 }
95 return false;
96}
97
99 bool write) {
100 FileAction file_action;
101 if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
102 AppendFileAction(file_action);
103 return true;
104 }
105 return false;
106}
107
109 if (idx < m_file_actions.size())
110 return &m_file_actions[idx];
111 return nullptr;
112}
113
115 for (size_t idx = 0, count = m_file_actions.size(); idx < count; ++idx) {
116 if (m_file_actions[idx].GetFD() == fd)
117 return &m_file_actions[idx];
118 }
119 return nullptr;
120}
121
125
127 m_working_dir = working_dir;
128}
129
131 return llvm::StringRef(m_plugin_name);
132}
133
135 m_plugin_name = std::string(plugin);
136}
137
139
141 m_shell = shell;
142 if (m_shell) {
144 m_flags.Set(lldb::eLaunchFlagLaunchInShell);
145 } else
146 m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
147}
148
150 if (separate)
151 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
152 else
153 m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
154}
155
157 if (expand)
158 m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
159 else
160 m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
161}
162
165 m_working_dir.Clear();
166 m_plugin_name.clear();
167 m_shell.Clear();
168 m_flags.Clear();
169 m_file_actions.clear();
170 m_resume_count = 0;
171 m_listener_sp.reset();
172 m_hijack_listener_sp.reset();
173}
174
176 int status) {
178 LLDB_LOG(log, "pid = {0}, signal = {1}, status = {2}", pid, signal, status);
179}
180
183 llvm::Expected<HostThread> maybe_thread =
185 if (!maybe_thread)
186 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), maybe_thread.takeError(),
187 "failed to launch host thread: {0}");
188 return true;
189 }
190 return false;
191}
192
194 if (enable)
195 m_flags.Set(lldb::eLaunchFlagDetachOnError);
196 else
197 m_flags.Clear(lldb::eLaunchFlagDetachOnError);
198}
199
202
203 bool stdin_free = GetFileActionForFD(STDIN_FILENO) == nullptr;
204 bool stdout_free = GetFileActionForFD(STDOUT_FILENO) == nullptr;
205 bool stderr_free = GetFileActionForFD(STDERR_FILENO) == nullptr;
206 bool any_free = stdin_free || stdout_free || stderr_free;
207 if (!any_free)
208 return llvm::Error::success();
209
210 LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
211
212#ifdef _WIN32
213 if (llvm::Error Err = m_pty->OpenPseudoConsole())
214 return Err;
215 return llvm::Error::success();
216#else
217 int open_flags = O_RDWR | O_NOCTTY | O_CLOEXEC;
218 if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
219 return Err;
220
221 const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
222
223 if (stdin_free)
224 AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
225
226 if (stdout_free)
227 AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
228
229 if (stderr_free)
230 AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
231 return llvm::Error::success();
232#endif
233}
234
236 Status &error, bool will_debug, bool first_arg_is_full_shell_command,
237 uint32_t num_resumes) {
238 error.Clear();
239
240 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
241 if (m_shell) {
242 std::string shell_executable = m_shell.GetPath();
243
244 const char **argv = GetArguments().GetConstArgumentVector();
245 if (argv == nullptr || argv[0] == nullptr)
246 return false;
247 Args shell_arguments;
248 shell_arguments.AppendArgument(shell_executable);
249 const llvm::Triple &triple = GetArchitecture().GetTriple();
250 if (triple.getOS() == llvm::Triple::Win32 &&
251 !triple.isWindowsCygwinEnvironment())
252 shell_arguments.AppendArgument(llvm::StringRef("/C"));
253 else
254 shell_arguments.AppendArgument(llvm::StringRef("-c"));
255
256 StreamString shell_command;
257 if (will_debug) {
258 // Add a modified PATH environment variable in case argv[0] is a
259 // relative path.
260 const char *argv0 = argv[0];
261 FileSpec arg_spec(argv0);
262 if (arg_spec.IsRelative()) {
263 // We have a relative path to our executable which may not work if we
264 // just try to run "a.out" (without it being converted to "./a.out")
265 FileSpec working_dir = GetWorkingDirectory();
266 // Be sure to put quotes around PATH's value in case any paths have
267 // spaces...
268 std::string new_path("PATH=\"");
269 const size_t empty_path_len = new_path.size();
270
271 if (working_dir) {
272 new_path += working_dir.GetPath();
273 } else {
274 llvm::SmallString<64> cwd;
275 if (! llvm::sys::fs::current_path(cwd))
276 new_path += cwd;
277 }
278 std::string curr_path;
279 if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
280 if (new_path.size() > empty_path_len)
281 new_path += ':';
282 new_path += curr_path;
283 }
284 new_path += "\" ";
285 shell_command.PutCString(new_path);
286 }
287
288 if (triple.getOS() != llvm::Triple::Win32 ||
289 triple.isWindowsCygwinEnvironment())
290 shell_command.PutCString("exec");
291
292 // Only Apple supports /usr/bin/arch being able to specify the
293 // architecture
294 if (GetArchitecture().IsValid() && // Valid architecture
295 GetArchitecture().GetTriple().getVendor() ==
296 llvm::Triple::Apple && // Apple only
297 GetArchitecture().GetCore() !=
298 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
299 {
300 shell_command.Printf(" /usr/bin/arch -arch %s",
301 GetArchitecture().GetArchitectureName());
302 // Set the resume count to 2:
303 // 1 - stop in shell
304 // 2 - stop in /usr/bin/arch
305 // 3 - then we will stop in our program
306 SetResumeCount(num_resumes + 1);
307 } else {
308 // Set the resume count to 1:
309 // 1 - stop in shell
310 // 2 - then we will stop in our program
311 SetResumeCount(num_resumes);
312 }
313 }
314
315 if (first_arg_is_full_shell_command) {
316 // There should only be one argument that is the shell command itself
317 // to be used as is
318 if (argv[0] && !argv[1])
319 shell_command.Printf("%s", argv[0]);
320 else
321 return false;
322 } else {
323 for (size_t i = 0; argv[i] != nullptr; ++i) {
324 std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
325 if (safe_arg.empty())
326 safe_arg = "\"\"";
327 // Add a space to separate this arg from the previous one.
328 shell_command.PutCString(" ");
329 shell_command.PutCString(safe_arg);
330 }
331 }
332 shell_arguments.AppendArgument(shell_command.GetString());
334 m_arguments = shell_arguments;
335 return true;
336 } else {
337 error = Status::FromErrorString("invalid shell path");
338 }
339 } else {
340 error = Status::FromErrorString("not launching in shell");
341 }
342 return false;
343}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
static bool separate(size_t count)
Definition UUID.cpp:29
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
static std::string GetShellSafeArgument(const FileSpec &shell, llvm::StringRef unsafe_arg)
Definition Args.cpp:394
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition Args.cpp:289
bool Duplicate(int fd, int dup_fd)
bool Open(int fd, const FileSpec &file_spec, bool read, bool write)
A file utility class.
Definition FileSpec.h:57
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:514
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
static const char * DEV_NULL
Definition FileSystem.h:32
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
static FileSystem & Instance()
static llvm::Expected< HostThread > StartMonitoringChildProcess(const MonitorChildProcessCallback &callback, lldb::pid_t pid)
Start monitoring a child process.
bool ProcessIDIsValid() const
Definition ProcessInfo.h:72
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
lldb::ListenerSP m_hijack_listener_sp
lldb::ListenerSP m_listener_sp
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:62
llvm::StringRef GetProcessPluginName() const
const FileSpec & GetShell() const
std::vector< FileAction > m_file_actions
bool AppendOpenFileAction(int fd, const FileSpec &file_spec, bool read, bool write)
bool AppendSuppressFileAction(int fd, bool read, bool write)
static void NoOpMonitorCallback(lldb::pid_t pid, int signal, int status)
A Monitor callback which does not take any action on process events.
const FileAction * GetFileActionAtIndex(size_t idx) const
void SetShell(const FileSpec &shell)
const FileAction * GetFileActionForFD(int fd) const
void SetProcessPluginName(llvm::StringRef plugin)
bool ConvertArgumentsForLaunchingInShell(Status &error, bool will_debug, bool first_arg_is_full_shell_command, uint32_t num_resumes)
bool AppendDuplicateFileAction(int fd, int dup_fd)
void AppendFileAction(const FileAction &info)
void SetLaunchInSeparateProcessGroup(bool separate)
void SetWorkingDirectory(const FileSpec &working_dir)
Host::MonitorChildProcessCallback m_monitor_callback
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
PseudoTerminal PTY
uint64_t pid_t
Definition lldb-types.h:83
#define O_NOCTTY