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
26#else
27#include <climits>
28#endif
29
30using namespace lldb;
31using namespace lldb_private;
32
33// ProcessLaunchInfo member functions
34
38#ifndef _WIN32
39 m_pty = std::make_shared<PTY>();
40#endif
41}
42
44 const FileSpec &stdout_file_spec,
45 const FileSpec &stderr_file_spec,
46 const FileSpec &working_directory,
47 uint32_t launch_flags)
48 : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
50#ifndef _WIN32
51 m_pty = std::make_shared<PTY>();
52#endif
53 if (stdin_file_spec) {
54 FileAction file_action;
55 const bool read = true;
56 const bool write = false;
57 if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
58 AppendFileAction(file_action);
59 }
60 if (stdout_file_spec) {
61 FileAction file_action;
62 const bool read = false;
63 const bool write = true;
64 if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
65 AppendFileAction(file_action);
66 }
67 if (stderr_file_spec) {
68 FileAction file_action;
69 const bool read = false;
70 const bool write = true;
71 if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
72 AppendFileAction(file_action);
73 }
74 if (working_directory)
75 SetWorkingDirectory(working_directory);
76}
77
79 FileAction file_action;
80 if (file_action.Close(fd)) {
81 AppendFileAction(file_action);
82 return true;
83 }
84 return false;
85}
86
88 FileAction file_action;
89 if (file_action.Duplicate(fd, dup_fd)) {
90 AppendFileAction(file_action);
91 return true;
92 }
93 return false;
94}
95
96#ifdef _WIN32
98 WindowsFileAction file_action;
99 if (file_action.Duplicate(fh, dup_fh)) {
100 AppendFileAction(file_action);
101 return true;
102 }
103 return false;
104}
105#endif
106
108 bool read, bool write) {
109 FileAction file_action;
110 if (file_action.Open(fd, file_spec, read, write)) {
111 AppendFileAction(file_action);
112 return true;
113 }
114 return false;
115}
116
118 bool write) {
119 FileAction file_action;
120 if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
121 AppendFileAction(file_action);
122 return true;
123 }
124 return false;
125}
126
128 if (idx < m_file_actions.size())
129 return &m_file_actions[idx];
130 return nullptr;
131}
132
134 for (size_t idx = 0, count = m_file_actions.size(); idx < count; ++idx) {
135 if (m_file_actions[idx].GetFD() == fd)
136 return &m_file_actions[idx];
137 }
138 return nullptr;
139}
140
142 if (GetFileActionForFD(fd))
143 return true;
144 for (size_t i = 0; i < GetNumFileActions(); ++i) {
145 const FileAction *act = GetFileActionAtIndex(i);
147 act->GetActionArgument() == fd)
148 return true;
149 }
150 return false;
151}
152
156
158 m_working_dir = working_dir;
159}
160
162 return llvm::StringRef(m_plugin_name);
163}
164
166 m_plugin_name = std::string(plugin);
167}
168
170
172 m_shell = shell;
173 if (m_shell) {
175 m_flags.Set(lldb::eLaunchFlagLaunchInShell);
176 } else
177 m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
178}
179
181 if (separate)
182 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
183 else
184 m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
185}
186
188 if (expand)
189 m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
190 else
191 m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
192}
193
196 m_working_dir.Clear();
197 m_plugin_name.clear();
198 m_shell.Clear();
199 m_flags.Clear();
200 m_file_actions.clear();
201 m_resume_count = 0;
202 m_listener_sp.reset();
203 m_hijack_listener_sp.reset();
204}
205
207 int status) {
209 LLDB_LOG(log, "pid = {0}, signal = {1}, status = {2}", pid, signal, status);
210}
211
214 llvm::Expected<HostThread> maybe_thread =
216 if (!maybe_thread)
217 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), maybe_thread.takeError(),
218 "failed to launch host thread: {0}");
219 return true;
220 }
221 return false;
222}
223
225 if (enable)
226 m_flags.Set(lldb::eLaunchFlagDetachOnError);
227 else
228 m_flags.Clear(lldb::eLaunchFlagDetachOnError);
229}
230
233
234 if (!m_pty)
235 m_pty = std::make_shared<PTY>();
236
237 bool stdin_free = GetFileActionForFD(STDIN_FILENO) == nullptr;
238 bool stdout_free = GetFileActionForFD(STDOUT_FILENO) == nullptr;
239 bool stderr_free = GetFileActionForFD(STDERR_FILENO) == nullptr;
240 bool any_free = stdin_free || stdout_free || stderr_free;
241 if (!any_free)
242 return llvm::Error::success();
243
244 LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
245
246#ifdef _WIN32
247 if (llvm::Error Err = m_pty->OpenPseudoConsole(m_stdio_window_size.cols,
249 return Err;
250 return llvm::Error::success();
251#else
252 int open_flags = O_RDWR | O_NOCTTY | O_CLOEXEC;
253 if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
254 return Err;
255
256 const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
257
258 if (stdin_free)
259 AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
260
261 if (stdout_free)
262 AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
263
264 if (stderr_free)
265 AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
266 return llvm::Error::success();
267#endif
268}
269
270#ifdef _WIN32
271llvm::Error ProcessLaunchInfo::SetUpPipeRedirection() {
272 if (!m_pty)
273 m_pty = std::make_shared<PTY>();
274 return m_pty->OpenAnonymousPipes();
275}
276#endif
277
279 Status &error, bool will_debug, bool first_arg_is_full_shell_command,
280 uint32_t num_resumes) {
281 error.Clear();
282
283 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
284 if (m_shell) {
285 std::string shell_executable = m_shell.GetPath();
286
287 const char **argv = GetArguments().GetConstArgumentVector();
288 if (argv == nullptr || argv[0] == nullptr)
289 return false;
290 Args shell_arguments;
291 shell_arguments.AppendArgument(shell_executable);
292 const llvm::Triple &triple = GetArchitecture().GetTriple();
293 if (triple.getOS() == llvm::Triple::Win32 &&
294 !triple.isWindowsCygwinEnvironment())
295 shell_arguments.AppendArgument(llvm::StringRef("/C"));
296 else
297 shell_arguments.AppendArgument(llvm::StringRef("-c"));
298
299 StreamString shell_command;
300 if (will_debug) {
301 // Add a modified PATH environment variable in case argv[0] is a
302 // relative path.
303 const char *argv0 = argv[0];
304 FileSpec arg_spec(argv0);
305 if (arg_spec.IsRelative()) {
306 // We have a relative path to our executable which may not work if we
307 // just try to run "a.out" (without it being converted to "./a.out")
308 FileSpec working_dir = GetWorkingDirectory();
309 // Be sure to put quotes around PATH's value in case any paths have
310 // spaces...
311 std::string new_path("PATH=\"");
312 const size_t empty_path_len = new_path.size();
313
314 if (working_dir) {
315 new_path += working_dir.GetPath();
316 } else {
317 llvm::SmallString<64> cwd;
318 if (! llvm::sys::fs::current_path(cwd))
319 new_path += cwd;
320 }
321 std::string curr_path;
322 if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
323 if (new_path.size() > empty_path_len)
324 new_path += ':';
325 new_path += curr_path;
326 }
327 new_path += "\" ";
328 shell_command.PutCString(new_path);
329 }
330
331 if (triple.getOS() != llvm::Triple::Win32 ||
332 triple.isWindowsCygwinEnvironment())
333 shell_command.PutCString("exec");
334
335 // Only Apple supports /usr/bin/arch being able to specify the
336 // architecture
337 if (GetArchitecture().IsValid() && // Valid architecture
338 GetArchitecture().GetTriple().getVendor() ==
339 llvm::Triple::Apple && // Apple only
340 GetArchitecture().GetCore() !=
341 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
342 {
343 shell_command.Printf(" /usr/bin/arch -arch %s",
344 GetArchitecture().GetArchitectureName());
345 // Set the resume count to 2:
346 // 1 - stop in shell
347 // 2 - stop in /usr/bin/arch
348 // 3 - then we will stop in our program
349 SetResumeCount(num_resumes + 1);
350 } else {
351 // Set the resume count to 1:
352 // 1 - stop in shell
353 // 2 - then we will stop in our program
354 SetResumeCount(num_resumes);
355 }
356 }
357
358 if (first_arg_is_full_shell_command) {
359 // There should only be one argument that is the shell command itself
360 // to be used as is
361 if (argv[0] && !argv[1])
362 shell_command.Printf("%s", argv[0]);
363 else
364 return false;
365 } else {
366 for (size_t i = 0; argv[i] != nullptr; ++i) {
367 std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
368 if (safe_arg.empty())
369 safe_arg = "\"\"";
370 // Add a space to separate this arg from the previous one.
371 shell_command.PutCString(" ");
372 shell_command.PutCString(safe_arg);
373 }
374 }
375 shell_arguments.AppendArgument(shell_command.GetString());
377 m_arguments = shell_arguments;
378 return true;
379 } else {
380 error = Status::FromErrorString("invalid shell path");
381 }
382 } else {
383 error = Status::FromErrorString("not launching in shell");
384 }
385 return false;
386}
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:364
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
void * HANDLE
static bool separate(size_t count)
Definition UUID.cpp:29
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:460
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
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
Action GetAction() const
Get the type of action.
Definition FileAction.h:59
bool Duplicate(int fd, int dup_fd)
Configure this action to duplicate a file descriptor.
int GetActionArgument() const
Get the action-specific argument.
Definition FileAction.h:65
bool Open(int fd, const FileSpec &file_spec, bool read, bool write)
Configure this action to open a file.
bool Close(int fd)
Configure this action to close a file descriptor.
A file utility class.
Definition FileSpec.h:57
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:510
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:70
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
lldb::ListenerSP m_hijack_listener_sp
lldb::ListenerSP m_listener_sp
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:60
llvm::StringRef GetProcessPluginName() const
const FileSpec & GetShell() const
void AppendFileAction(const FileActionImpl &info)
bool IsFDRedirected(int fd) const
Returns true if fd has an explicit file action, or is the destination of a duplicate action.
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
std::vector< FileActionImpl > m_file_actions
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 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:63
A Windows-specific extension of FileAction that supports HANDLE-based file operations in addition to ...
bool Duplicate(HANDLE fh, HANDLE dup_fh)
Configure this action to duplicate a Windows file handle.
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:327
uint64_t pid_t
Definition lldb-types.h:83
#define O_NOCTTY