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())
248 return Err;
249 return llvm::Error::success();
250#else
251 int open_flags = O_RDWR | O_NOCTTY | O_CLOEXEC;
252 if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
253 return Err;
254
255 const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
256
257 if (stdin_free)
258 AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
259
260 if (stdout_free)
261 AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
262
263 if (stderr_free)
264 AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
265 return llvm::Error::success();
266#endif
267}
268
269#ifdef _WIN32
270llvm::Error ProcessLaunchInfo::SetUpPipeRedirection() {
271 if (!m_pty)
272 m_pty = std::make_shared<PTY>();
273 return m_pty->OpenAnonymousPipes();
274}
275#endif
276
278 Status &error, bool will_debug, bool first_arg_is_full_shell_command,
279 uint32_t num_resumes) {
280 error.Clear();
281
282 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
283 if (m_shell) {
284 std::string shell_executable = m_shell.GetPath();
285
286 const char **argv = GetArguments().GetConstArgumentVector();
287 if (argv == nullptr || argv[0] == nullptr)
288 return false;
289 Args shell_arguments;
290 shell_arguments.AppendArgument(shell_executable);
291 const llvm::Triple &triple = GetArchitecture().GetTriple();
292 if (triple.getOS() == llvm::Triple::Win32 &&
293 !triple.isWindowsCygwinEnvironment())
294 shell_arguments.AppendArgument(llvm::StringRef("/C"));
295 else
296 shell_arguments.AppendArgument(llvm::StringRef("-c"));
297
298 StreamString shell_command;
299 if (will_debug) {
300 // Add a modified PATH environment variable in case argv[0] is a
301 // relative path.
302 const char *argv0 = argv[0];
303 FileSpec arg_spec(argv0);
304 if (arg_spec.IsRelative()) {
305 // We have a relative path to our executable which may not work if we
306 // just try to run "a.out" (without it being converted to "./a.out")
307 FileSpec working_dir = GetWorkingDirectory();
308 // Be sure to put quotes around PATH's value in case any paths have
309 // spaces...
310 std::string new_path("PATH=\"");
311 const size_t empty_path_len = new_path.size();
312
313 if (working_dir) {
314 new_path += working_dir.GetPath();
315 } else {
316 llvm::SmallString<64> cwd;
317 if (! llvm::sys::fs::current_path(cwd))
318 new_path += cwd;
319 }
320 std::string curr_path;
321 if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
322 if (new_path.size() > empty_path_len)
323 new_path += ':';
324 new_path += curr_path;
325 }
326 new_path += "\" ";
327 shell_command.PutCString(new_path);
328 }
329
330 if (triple.getOS() != llvm::Triple::Win32 ||
331 triple.isWindowsCygwinEnvironment())
332 shell_command.PutCString("exec");
333
334 // Only Apple supports /usr/bin/arch being able to specify the
335 // architecture
336 if (GetArchitecture().IsValid() && // Valid architecture
337 GetArchitecture().GetTriple().getVendor() ==
338 llvm::Triple::Apple && // Apple only
339 GetArchitecture().GetCore() !=
340 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
341 {
342 shell_command.Printf(" /usr/bin/arch -arch %s",
343 GetArchitecture().GetArchitectureName());
344 // Set the resume count to 2:
345 // 1 - stop in shell
346 // 2 - stop in /usr/bin/arch
347 // 3 - then we will stop in our program
348 SetResumeCount(num_resumes + 1);
349 } else {
350 // Set the resume count to 1:
351 // 1 - stop in shell
352 // 2 - then we will stop in our program
353 SetResumeCount(num_resumes);
354 }
355 }
356
357 if (first_arg_is_full_shell_command) {
358 // There should only be one argument that is the shell command itself
359 // to be used as is
360 if (argv[0] && !argv[1])
361 shell_command.Printf("%s", argv[0]);
362 else
363 return false;
364 } else {
365 for (size_t i = 0; argv[i] != nullptr; ++i) {
366 std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
367 if (safe_arg.empty())
368 safe_arg = "\"\"";
369 // Add a space to separate this arg from the previous one.
370 shell_command.PutCString(" ");
371 shell_command.PutCString(safe_arg);
372 }
373 }
374 shell_arguments.AppendArgument(shell_command.GetString());
376 m_arguments = shell_arguments;
377 return true;
378 } else {
379 error = Status::FromErrorString("invalid shell path");
380 }
381 } else {
382 error = Status::FromErrorString("not launching in shell");
383 }
384 return false;
385}
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:62
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:68
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: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
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