Bug Summary

File:tools/lldb/source/Host/common/Host.cpp
Warning:line 289, column 5
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Host.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D HAVE_ROUND -D LLDB_CONFIGURATION_RELEASE -D LLDB_USE_BUILTIN_DEMANGLER -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/lldb/source/Host -I /build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/lldb/include -I /build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -I /usr/include/python2.7 -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/lldb/source/Host -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp
1//===-- Host.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// C includes
11#include <errno(*__errno_location ()).h>
12#include <limits.h>
13#include <stdlib.h>
14#include <sys/types.h>
15#ifndef _WIN32
16#include <dlfcn.h>
17#include <grp.h>
18#include <netdb.h>
19#include <pwd.h>
20#include <sys/stat.h>
21#include <unistd.h>
22#endif
23
24#if defined(__APPLE__)
25#include <mach-o/dyld.h>
26#include <mach/mach_init.h>
27#include <mach/mach_port.h>
28#endif
29
30#if defined(__linux__1) || defined(__FreeBSD__) || \
31 defined(__FreeBSD_kernel__) || defined(__APPLE__) || \
32 defined(__NetBSD__) || defined(__OpenBSD__)
33#if !defined(__ANDROID__)
34#include <spawn.h>
35#endif
36#include <sys/syscall.h>
37#include <sys/wait.h>
38#endif
39
40#if defined(__FreeBSD__)
41#include <pthread_np.h>
42#endif
43
44#if defined(__NetBSD__)
45#include <lwp.h>
46#endif
47
48// C++ Includes
49#include <csignal>
50
51#include "lldb/Host/Host.h"
52#include "lldb/Host/HostInfo.h"
53#include "lldb/Host/HostProcess.h"
54#include "lldb/Host/MonitoringProcessLauncher.h"
55#include "lldb/Host/Predicate.h"
56#include "lldb/Host/ProcessLauncher.h"
57#include "lldb/Host/ThreadLauncher.h"
58#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
59#include "lldb/Target/FileAction.h"
60#include "lldb/Target/ProcessLaunchInfo.h"
61#include "lldb/Target/UnixSignals.h"
62#include "lldb/Utility/DataBufferLLVM.h"
63#include "lldb/Utility/FileSpec.h"
64#include "lldb/Utility/Log.h"
65#include "lldb/Utility/Status.h"
66#include "lldb/lldb-private-forward.h"
67#include "llvm/ADT/SmallString.h"
68#include "llvm/ADT/StringSwitch.h"
69#include "llvm/Support/Errno.h"
70#include "llvm/Support/FileSystem.h"
71
72#if defined(_WIN32)
73#include "lldb/Host/windows/ConnectionGenericFileWindows.h"
74#include "lldb/Host/windows/ProcessLauncherWindows.h"
75#else
76#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
77#endif
78
79#if defined(__APPLE__)
80#ifndef _POSIX_SPAWN_DISABLE_ASLR
81#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
82#endif
83
84extern "C" {
85int __pthread_chdir(const char *path);
86int __pthread_fchdir(int fildes);
87}
88
89#endif
90
91using namespace lldb;
92using namespace lldb_private;
93
94#if !defined(__APPLE__) && !defined(_WIN32)
95struct MonitorInfo {
96 lldb::pid_t pid; // The process ID to monitor
97 Host::MonitorChildProcessCallback
98 callback; // The callback function to call when "pid" exits or signals
99 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
100};
101
102static thread_result_t MonitorChildProcessThreadFunction(void *arg);
103
104HostThread Host::StartMonitoringChildProcess(
105 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
106 bool monitor_signals) {
107 MonitorInfo *info_ptr = new MonitorInfo();
108
109 info_ptr->pid = pid;
110 info_ptr->callback = callback;
111 info_ptr->monitor_signals = monitor_signals;
112
113 char thread_name[256];
114 ::snprintf(thread_name, sizeof(thread_name),
115 "<lldb.host.wait4(pid=%" PRIu64"l" "u" ")>", pid);
116 return ThreadLauncher::LaunchThread(
117 thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL__null);
118}
119
120#ifndef __linux__1
121//------------------------------------------------------------------
122// Scoped class that will disable thread canceling when it is
123// constructed, and exception safely restore the previous value it
124// when it goes out of scope.
125//------------------------------------------------------------------
126class ScopedPThreadCancelDisabler {
127public:
128 ScopedPThreadCancelDisabler() {
129 // Disable the ability for this thread to be cancelled
130 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLEPTHREAD_CANCEL_DISABLE, &m_old_state);
131 if (err != 0)
132 m_old_state = -1;
133 }
134
135 ~ScopedPThreadCancelDisabler() {
136 // Restore the ability for this thread to be cancelled to what it
137 // previously was.
138 if (m_old_state != -1)
139 ::pthread_setcancelstate(m_old_state, 0);
140 }
141
142private:
143 int m_old_state; // Save the old cancelability state.
144};
145#endif // __linux__
146
147#ifdef __linux__1
148#if defined(__GNUC__4) && (__GNUC__4 < 4 || (__GNUC__4 == 4 && __GNUC_MINOR__2 < 8))
149static __thread volatile sig_atomic_t g_usr1_called;
150#else
151static thread_local volatile sig_atomic_t g_usr1_called;
152#endif
153
154static void SigUsr1Handler(int) { g_usr1_called = 1; }
155#endif // __linux__
156
157static bool CheckForMonitorCancellation() {
158#ifdef __linux__1
159 if (g_usr1_called) {
160 g_usr1_called = 0;
161 return true;
162 }
163#else
164 ::pthread_testcancel();
165#endif
166 return false;
167}
168
169static thread_result_t MonitorChildProcessThreadFunction(void *arg) {
170 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1)));
171 const char *function = __FUNCTION__;
172 if (log)
1
Assuming 'log' is null
2
Taking false branch
173 log->Printf("%s (arg = %p) thread starting...", function, arg);
174
175 MonitorInfo *info = (MonitorInfo *)arg;
176
177 const Host::MonitorChildProcessCallback callback = info->callback;
178 const bool monitor_signals = info->monitor_signals;
179
180 assert(info->pid <= UINT32_MAX)(static_cast <bool> (info->pid <= (4294967295U)) ?
void (0) : __assert_fail ("info->pid <= UINT32_MAX", "/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, 180, __extension__ __PRETTY_FUNCTION__))
;
181 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
3
Assuming 'monitor_signals' is 0
4
'?' condition is false
182
183 delete info;
5
Memory is released
184
185 int status = -1;
186#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
187#define __WALL0x40000000 0
188#endif
189 const int options = __WALL0x40000000;
190
191#ifdef __linux__1
192 // This signal is only used to interrupt the thread from waitpid
193 struct sigaction sigUsr1Action;
194 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
195 sigUsr1Action.sa_handler__sigaction_handler.sa_handler = SigUsr1Handler;
196 ::sigaction(SIGUSR110, &sigUsr1Action, nullptr);
197#endif // __linux__
198
199 while (1) {
6
Loop condition is true. Entering loop body
200 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1));
201 if (log)
7
Assuming 'log' is null
8
Taking false branch
202 log->Printf("%s ::waitpid (pid = %" PRIi32"i" ", &status, options = %i)...",
203 function, pid, options);
204
205 if (CheckForMonitorCancellation())
9
Taking true branch
206 break;
10
Execution continues on line 287
207
208 // Get signals from all children with same process group of pid
209 const ::pid_t wait_pid = ::waitpid(pid, &status, options);
210
211 if (CheckForMonitorCancellation())
212 break;
213
214 if (wait_pid == -1) {
215 if (errno(*__errno_location ()) == EINTR4)
216 continue;
217 else {
218 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, __func__, "arg = {0}, thread exiting because waitpid failed ({1})..."
, arg, llvm::sys::StrError()); } while (0)
219 "arg = {0}, thread exiting because waitpid failed ({1})...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, __func__, "arg = {0}, thread exiting because waitpid failed ({1})..."
, arg, llvm::sys::StrError()); } while (0)
220 arg, llvm::sys::StrError())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, __func__, "arg = {0}, thread exiting because waitpid failed ({1})..."
, arg, llvm::sys::StrError()); } while (0)
;
221 break;
222 }
223 } else if (wait_pid > 0) {
224 bool exited = false;
225 int signal = 0;
226 int exit_status = 0;
227 const char *status_cstr = NULL__null;
228 if (WIFSTOPPED(status)(((status) & 0xff) == 0x7f)) {
229 signal = WSTOPSIG(status)(((status) & 0xff00) >> 8);
230 status_cstr = "STOPPED";
231 } else if (WIFEXITED(status)(((status) & 0x7f) == 0)) {
232 exit_status = WEXITSTATUS(status)(((status) & 0xff00) >> 8);
233 status_cstr = "EXITED";
234 exited = true;
235 } else if (WIFSIGNALED(status)(((signed char) (((status) & 0x7f) + 1) >> 1) > 0
)
) {
236 signal = WTERMSIG(status)((status) & 0x7f);
237 status_cstr = "SIGNALED";
238 if (wait_pid == abs(pid)) {
239 exited = true;
240 exit_status = -1;
241 }
242 } else {
243 status_cstr = "(\?\?\?)";
244 }
245
246 // Scope for pthread_cancel_disabler
247 {
248#ifndef __linux__1
249 ScopedPThreadCancelDisabler pthread_cancel_disabler;
250#endif
251
252 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1));
253 if (log)
254 log->Printf("%s ::waitpid (pid = %" PRIi32"i"
255 ", &status, options = %i) => pid = %" PRIi32"i"
256 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
257 function, pid, options, wait_pid, status, status_cstr,
258 signal, exit_status);
259
260 if (exited || (signal != 0 && monitor_signals)) {
261 bool callback_return = false;
262 if (callback)
263 callback_return = callback(wait_pid, exited, signal, exit_status);
264
265 // If our process exited, then this thread should exit
266 if (exited && wait_pid == abs(pid)) {
267 if (log)
268 log->Printf("%s (arg = %p) thread exiting because pid received "
269 "exit signal...",
270 __FUNCTION__, arg);
271 break;
272 }
273 // If the callback returns true, it means this process should
274 // exit
275 if (callback_return) {
276 if (log)
277 log->Printf("%s (arg = %p) thread exiting because callback "
278 "returned true...",
279 __FUNCTION__, arg);
280 break;
281 }
282 }
283 }
284 }
285 }
286
287 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1));
288 if (log)
11
Assuming 'log' is non-null
12
Taking true branch
289 log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
13
Use of memory after it is freed
290
291 return NULL__null;
292}
293
294#endif // #if !defined (__APPLE__) && !defined (_WIN32)
295
296#if !defined(__APPLE__)
297
298void Host::SystemLog(SystemLogType type, const char *format, va_list args) {
299 vfprintf(stderrstderr, format, args);
300}
301
302#endif
303
304void Host::SystemLog(SystemLogType type, const char *format, ...) {
305 va_list args;
306 va_start(args, format)__builtin_va_start(args, format);
307 SystemLog(type, format, args);
308 va_end(args)__builtin_va_end(args);
309}
310
311lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); }
312
313#ifndef _WIN32
314
315lldb::thread_t Host::GetCurrentThread() {
316 return lldb::thread_t(pthread_self());
317}
318
319const char *Host::GetSignalAsCString(int signo) {
320 switch (signo) {
321 case SIGHUP1:
322 return "SIGHUP"; // 1 hangup
323 case SIGINT2:
324 return "SIGINT"; // 2 interrupt
325 case SIGQUIT3:
326 return "SIGQUIT"; // 3 quit
327 case SIGILL4:
328 return "SIGILL"; // 4 illegal instruction (not reset when caught)
329 case SIGTRAP5:
330 return "SIGTRAP"; // 5 trace trap (not reset when caught)
331 case SIGABRT6:
332 return "SIGABRT"; // 6 abort()
333#if defined(SIGPOLL29)
334#if !defined(SIGIO29) || (SIGPOLL29 != SIGIO29)
335 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
336 // fail with 'multiple define cases with same value'
337 case SIGPOLL29:
338 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
339#endif
340#endif
341#if defined(SIGEMT)
342 case SIGEMT:
343 return "SIGEMT"; // 7 EMT instruction
344#endif
345 case SIGFPE8:
346 return "SIGFPE"; // 8 floating point exception
347 case SIGKILL9:
348 return "SIGKILL"; // 9 kill (cannot be caught or ignored)
349 case SIGBUS7:
350 return "SIGBUS"; // 10 bus error
351 case SIGSEGV11:
352 return "SIGSEGV"; // 11 segmentation violation
353 case SIGSYS31:
354 return "SIGSYS"; // 12 bad argument to system call
355 case SIGPIPE13:
356 return "SIGPIPE"; // 13 write on a pipe with no one to read it
357 case SIGALRM14:
358 return "SIGALRM"; // 14 alarm clock
359 case SIGTERM15:
360 return "SIGTERM"; // 15 software termination signal from kill
361 case SIGURG23:
362 return "SIGURG"; // 16 urgent condition on IO channel
363 case SIGSTOP19:
364 return "SIGSTOP"; // 17 sendable stop signal not from tty
365 case SIGTSTP20:
366 return "SIGTSTP"; // 18 stop signal from tty
367 case SIGCONT18:
368 return "SIGCONT"; // 19 continue a stopped process
369 case SIGCHLD17:
370 return "SIGCHLD"; // 20 to parent on child stop or exit
371 case SIGTTIN21:
372 return "SIGTTIN"; // 21 to readers pgrp upon background tty read
373 case SIGTTOU22:
374 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
375#if defined(SIGIO29)
376 case SIGIO29:
377 return "SIGIO"; // 23 input/output possible signal
378#endif
379 case SIGXCPU24:
380 return "SIGXCPU"; // 24 exceeded CPU time limit
381 case SIGXFSZ25:
382 return "SIGXFSZ"; // 25 exceeded file size limit
383 case SIGVTALRM26:
384 return "SIGVTALRM"; // 26 virtual time alarm
385 case SIGPROF27:
386 return "SIGPROF"; // 27 profiling time alarm
387#if defined(SIGWINCH28)
388 case SIGWINCH28:
389 return "SIGWINCH"; // 28 window size changes
390#endif
391#if defined(SIGINFO)
392 case SIGINFO:
393 return "SIGINFO"; // 29 information request
394#endif
395 case SIGUSR110:
396 return "SIGUSR1"; // 30 user defined signal 1
397 case SIGUSR212:
398 return "SIGUSR2"; // 31 user defined signal 2
399 default:
400 break;
401 }
402 return NULL__null;
403}
404
405#endif
406
407#if !defined(__APPLE__) // see Host.mm
408
409bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) {
410 bundle.Clear();
411 return false;
412}
413
414bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; }
415#endif
416
417#ifndef _WIN32
418
419FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
420 FileSpec module_filespec;
421#if !defined(__ANDROID__)
422 Dl_info info;
423 if (::dladdr(host_addr, &info)) {
424 if (info.dli_fname)
425 module_filespec.SetFile(info.dli_fname, true);
426 }
427#endif
428 return module_filespec;
429}
430
431#endif
432
433#if !defined(__linux__1)
434bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) {
435 return false;
436}
437#endif
438
439struct ShellInfo {
440 ShellInfo()
441 : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID0), signo(-1),
442 status(-1) {}
443
444 lldb_private::Predicate<bool> process_reaped;
445 lldb::pid_t pid;
446 int signo;
447 int status;
448};
449
450static bool
451MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid,
452 bool exited, // True if the process did exit
453 int signo, // Zero for no signal
454 int status) // Exit value of process if signal is zero
455{
456 shell_info->pid = pid;
457 shell_info->signo = signo;
458 shell_info->status = status;
459 // Let the thread running Host::RunShellCommand() know that the process
460 // exited and that ShellInfo has been filled in by broadcasting to it
461 shell_info->process_reaped.SetValue(true, eBroadcastAlways);
462 return true;
463}
464
465Status Host::RunShellCommand(const char *command, const FileSpec &working_dir,
466 int *status_ptr, int *signo_ptr,
467 std::string *command_output_ptr,
468 uint32_t timeout_sec, bool run_in_default_shell) {
469 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr,
470 command_output_ptr, timeout_sec, run_in_default_shell);
471}
472
473Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir,
474 int *status_ptr, int *signo_ptr,
475 std::string *command_output_ptr,
476 uint32_t timeout_sec, bool run_in_default_shell) {
477 Status error;
478 ProcessLaunchInfo launch_info;
479 launch_info.SetArchitecture(HostInfo::GetArchitecture());
480 if (run_in_default_shell) {
481 // Run the command in a shell
482 launch_info.SetShell(HostInfo::GetDefaultShell());
483 launch_info.GetArguments().AppendArguments(args);
484 const bool localhost = true;
485 const bool will_debug = false;
486 const bool first_arg_is_full_shell_command = false;
487 launch_info.ConvertArgumentsForLaunchingInShell(
488 error, localhost, will_debug, first_arg_is_full_shell_command, 0);
489 } else {
490 // No shell, just run it
491 const bool first_arg_is_executable = true;
492 launch_info.SetArguments(args, first_arg_is_executable);
493 }
494
495 if (working_dir)
496 launch_info.SetWorkingDirectory(working_dir);
497 llvm::SmallString<PATH_MAX4096> output_file_path;
498
499 if (command_output_ptr) {
500 // Create a temporary file to get the stdout/stderr and redirect the
501 // output of the command into this file. We will later read this file
502 // if all goes well and fill the data into "command_output_ptr"
503 FileSpec tmpdir_file_spec;
504 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) {
505 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
506 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
507 output_file_path);
508 } else {
509 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
510 output_file_path);
511 }
512 }
513
514 FileSpec output_file_spec{output_file_path.c_str(), false};
515
516 launch_info.AppendSuppressFileAction(STDIN_FILENO0, true, false);
517 if (output_file_spec) {
518 launch_info.AppendOpenFileAction(STDOUT_FILENO1, output_file_spec, false,
519 true);
520 launch_info.AppendDuplicateFileAction(STDOUT_FILENO1, STDERR_FILENO2);
521 } else {
522 launch_info.AppendSuppressFileAction(STDOUT_FILENO1, false, true);
523 launch_info.AppendSuppressFileAction(STDERR_FILENO2, false, true);
524 }
525
526 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
527 const bool monitor_signals = false;
528 launch_info.SetMonitorProcessCallback(
529 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
530 std::placeholders::_2, std::placeholders::_3,
531 std::placeholders::_4),
532 monitor_signals);
533
534 error = LaunchProcess(launch_info);
535 const lldb::pid_t pid = launch_info.GetProcessID();
536
537 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID0)
538 error.SetErrorString("failed to get process ID");
539
540 if (error.Success()) {
541 bool timed_out = false;
542 shell_info_sp->process_reaped.WaitForValueEqualTo(
543 true, std::chrono::seconds(timeout_sec), &timed_out);
544 if (timed_out) {
545 error.SetErrorString("timed out waiting for shell command to complete");
546
547 // Kill the process since it didn't complete within the timeout specified
548 Kill(pid, SIGKILL9);
549 // Wait for the monitor callback to get the message
550 timed_out = false;
551 shell_info_sp->process_reaped.WaitForValueEqualTo(
552 true, std::chrono::seconds(1), &timed_out);
553 } else {
554 if (status_ptr)
555 *status_ptr = shell_info_sp->status;
556
557 if (signo_ptr)
558 *signo_ptr = shell_info_sp->signo;
559
560 if (command_output_ptr) {
561 command_output_ptr->clear();
562 uint64_t file_size = output_file_spec.GetByteSize();
563 if (file_size > 0) {
564 if (file_size > command_output_ptr->max_size()) {
565 error.SetErrorStringWithFormat(
566 "shell command output is too large to fit into a std::string");
567 } else {
568 auto Buffer =
569 DataBufferLLVM::CreateFromPath(output_file_spec.GetPath());
570 if (error.Success())
571 command_output_ptr->assign(Buffer->GetChars(),
572 Buffer->GetByteSize());
573 }
574 }
575 }
576 }
577 }
578
579 llvm::sys::fs::remove(output_file_spec.GetPath());
580 return error;
581}
582
583// The functions below implement process launching for non-Apple-based platforms
584#if !defined(__APPLE__)
585Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) {
586 std::unique_ptr<ProcessLauncher> delegate_launcher;
587#if defined(_WIN32)
588 delegate_launcher.reset(new ProcessLauncherWindows());
589#else
590 delegate_launcher.reset(new ProcessLauncherPosixFork());
591#endif
592 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
593
594 Status error;
595 HostProcess process = launcher.LaunchProcess(launch_info, error);
596
597 // TODO(zturner): It would be better if the entire HostProcess were returned
598 // instead of writing
599 // it into this structure.
600 launch_info.SetProcessID(process.GetProcessId());
601
602 return error;
603}
604#endif // !defined(__APPLE__)
605
606#ifndef _WIN32
607void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); }
608
609#endif
610
611#if !defined(__APPLE__)
612bool Host::OpenFileInExternalEditor(const FileSpec &file_spec,
613 uint32_t line_no) {
614 return false;
615}
616
617#endif
618
619const UnixSignalsSP &Host::GetUnixSignals() {
620 static const auto s_unix_signals_sp =
621 UnixSignals::Create(HostInfo::GetArchitecture());
622 return s_unix_signals_sp;
623}
624
625std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) {
626#if defined(_WIN32)
627 if (url.startswith("file://"))
628 return std::unique_ptr<Connection>(new ConnectionGenericFile());
629#endif
630 return std::unique_ptr<Connection>(new ConnectionFileDescriptor());
631}
632
633#if defined(LLVM_ON_UNIX1)
634WaitStatus WaitStatus::Decode(int wstatus) {
635 if (WIFEXITED(wstatus)(((wstatus) & 0x7f) == 0))
636 return {Exit, uint8_t(WEXITSTATUS(wstatus)(((wstatus) & 0xff00) >> 8))};
637 else if (WIFSIGNALED(wstatus)(((signed char) (((wstatus) & 0x7f) + 1) >> 1) >
0)
)
638 return {Signal, uint8_t(WTERMSIG(wstatus)((wstatus) & 0x7f))};
639 else if (WIFSTOPPED(wstatus)(((wstatus) & 0xff) == 0x7f))
640 return {Stop, uint8_t(WSTOPSIG(wstatus)(((wstatus) & 0xff00) >> 8))};
641 llvm_unreachable("Unknown wait status")::llvm::llvm_unreachable_internal("Unknown wait status", "/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, 641)
;
642}
643#endif
644
645void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS,
646 raw_ostream &OS,
647 StringRef Options) {
648 if (Options == "g") {
649 char type;
650 switch (WS.type) {
651 case WaitStatus::Exit:
652 type = 'W';
653 break;
654 case WaitStatus::Signal:
655 type = 'X';
656 break;
657 case WaitStatus::Stop:
658 type = 'S';
659 break;
660 }
661 OS << formatv("{0}{1:x-2}", type, WS.status);
662 return;
663 }
664
665 assert(Options.empty())(static_cast <bool> (Options.empty()) ? void (0) : __assert_fail
("Options.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/lldb/source/Host/common/Host.cpp"
, 665, __extension__ __PRETTY_FUNCTION__))
;
666 const char *desc;
667 switch(WS.type) {
668 case WaitStatus::Exit:
669 desc = "Exited with status";
670 break;
671 case WaitStatus::Signal:
672 desc = "Killed by signal";
673 break;
674 case WaitStatus::Stop:
675 desc = "Stopped by signal";
676 break;
677 }
678 OS << desc << " " << int(WS.status);
679}