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
144
146 m_working_dir = working_dir;
147}
148
150 return llvm::StringRef(m_plugin_name);
151}
152
154 m_plugin_name = std::string(plugin);
155}
156
158
160 m_shell = shell;
161 if (m_shell) {
163 m_flags.Set(lldb::eLaunchFlagLaunchInShell);
164 } else
165 m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
166}
167
169 if (separate)
170 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
171 else
172 m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
173}
174
176 if (expand)
177 m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
178 else
179 m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
180}
181
184 m_working_dir.Clear();
185 m_plugin_name.clear();
186 m_shell.Clear();
187 m_flags.Clear();
188 m_file_actions.clear();
189 m_resume_count = 0;
190 m_listener_sp.reset();
191 m_hijack_listener_sp.reset();
192}
193
195 int status) {
197 LLDB_LOG(log, "pid = {0}, signal = {1}, status = {2}", pid, signal, status);
198}
199
202 llvm::Expected<HostThread> maybe_thread =
204 if (!maybe_thread)
205 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), maybe_thread.takeError(),
206 "failed to launch host thread: {0}");
207 return true;
208 }
209 return false;
210}
211
213 if (enable)
214 m_flags.Set(lldb::eLaunchFlagDetachOnError);
215 else
216 m_flags.Clear(lldb::eLaunchFlagDetachOnError);
217}
218
221
222 if (!m_pty)
223 m_pty = std::make_shared<PTY>();
224
225 bool stdin_free = GetFileActionForFD(STDIN_FILENO) == nullptr;
226 bool stdout_free = GetFileActionForFD(STDOUT_FILENO) == nullptr;
227 bool stderr_free = GetFileActionForFD(STDERR_FILENO) == nullptr;
228 bool any_free = stdin_free || stdout_free || stderr_free;
229 if (!any_free)
230 return llvm::Error::success();
231
232 LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
233
234#ifdef _WIN32
235 if (llvm::Error Err = m_pty->OpenPseudoConsole())
236 return Err;
237 return llvm::Error::success();
238#else
239 int open_flags = O_RDWR | O_NOCTTY | O_CLOEXEC;
240 if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
241 return Err;
242
243 const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
244
245 if (stdin_free)
246 AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
247
248 if (stdout_free)
249 AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
250
251 if (stderr_free)
252 AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
253 return llvm::Error::success();
254#endif
255}
256
257#ifdef _WIN32
258llvm::Error ProcessLaunchInfo::SetUpPipeRedirection() {
259 if (!m_pty)
260 m_pty = std::make_shared<PTY>();
261 return m_pty->OpenAnonymousPipes();
262}
263#endif
264
266 Status &error, bool will_debug, bool first_arg_is_full_shell_command,
267 uint32_t num_resumes) {
268 error.Clear();
269
270 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
271 if (m_shell) {
272 std::string shell_executable = m_shell.GetPath();
273
274 const char **argv = GetArguments().GetConstArgumentVector();
275 if (argv == nullptr || argv[0] == nullptr)
276 return false;
277 Args shell_arguments;
278 shell_arguments.AppendArgument(shell_executable);
279 const llvm::Triple &triple = GetArchitecture().GetTriple();
280 if (triple.getOS() == llvm::Triple::Win32 &&
281 !triple.isWindowsCygwinEnvironment())
282 shell_arguments.AppendArgument(llvm::StringRef("/C"));
283 else
284 shell_arguments.AppendArgument(llvm::StringRef("-c"));
285
286 StreamString shell_command;
287 if (will_debug) {
288 // Add a modified PATH environment variable in case argv[0] is a
289 // relative path.
290 const char *argv0 = argv[0];
291 FileSpec arg_spec(argv0);
292 if (arg_spec.IsRelative()) {
293 // We have a relative path to our executable which may not work if we
294 // just try to run "a.out" (without it being converted to "./a.out")
295 FileSpec working_dir = GetWorkingDirectory();
296 // Be sure to put quotes around PATH's value in case any paths have
297 // spaces...
298 std::string new_path("PATH=\"");
299 const size_t empty_path_len = new_path.size();
300
301 if (working_dir) {
302 new_path += working_dir.GetPath();
303 } else {
304 llvm::SmallString<64> cwd;
305 if (! llvm::sys::fs::current_path(cwd))
306 new_path += cwd;
307 }
308 std::string curr_path;
309 if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
310 if (new_path.size() > empty_path_len)
311 new_path += ':';
312 new_path += curr_path;
313 }
314 new_path += "\" ";
315 shell_command.PutCString(new_path);
316 }
317
318 if (triple.getOS() != llvm::Triple::Win32 ||
319 triple.isWindowsCygwinEnvironment())
320 shell_command.PutCString("exec");
321
322 // Only Apple supports /usr/bin/arch being able to specify the
323 // architecture
324 if (GetArchitecture().IsValid() && // Valid architecture
325 GetArchitecture().GetTriple().getVendor() ==
326 llvm::Triple::Apple && // Apple only
327 GetArchitecture().GetCore() !=
328 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
329 {
330 shell_command.Printf(" /usr/bin/arch -arch %s",
331 GetArchitecture().GetArchitectureName());
332 // Set the resume count to 2:
333 // 1 - stop in shell
334 // 2 - stop in /usr/bin/arch
335 // 3 - then we will stop in our program
336 SetResumeCount(num_resumes + 1);
337 } else {
338 // Set the resume count to 1:
339 // 1 - stop in shell
340 // 2 - then we will stop in our program
341 SetResumeCount(num_resumes);
342 }
343 }
344
345 if (first_arg_is_full_shell_command) {
346 // There should only be one argument that is the shell command itself
347 // to be used as is
348 if (argv[0] && !argv[1])
349 shell_command.Printf("%s", argv[0]);
350 else
351 return false;
352 } else {
353 for (size_t i = 0; argv[i] != nullptr; ++i) {
354 std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
355 if (safe_arg.empty())
356 safe_arg = "\"\"";
357 // Add a space to separate this arg from the previous one.
358 shell_command.PutCString(" ");
359 shell_command.PutCString(safe_arg);
360 }
361 }
362 shell_arguments.AppendArgument(shell_command.GetString());
364 m_arguments = shell_arguments;
365 return true;
366 } else {
367 error = Status::FromErrorString("invalid shell path");
368 }
369 } else {
370 error = Status::FromErrorString("not launching in shell");
371 }
372 return false;
373}
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:399
void * HANDLE
static bool separate(size_t count)
Definition UUID.cpp:29
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:457
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
bool Duplicate(int fd, int dup_fd)
Configure this action to duplicate a file descriptor.
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 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:65
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:332
uint64_t pid_t
Definition lldb-types.h:83
#define O_NOCTTY