This source file includes following definitions.
- GetEnvironment
- SetEnvironment
- SetSignalMask
- ResetChildSignalHandlersToDefaults
- sys_rt_sigaction
- ResetChildSignalHandlersToDefaults
- CloseSuperfluousFds
- LaunchProcess
- LaunchProcess
- RaiseProcessToHighPriority
- GetAppOutput
- GetAppOutput
- GetAppOutputRestricted
- GetAppOutputWithExitCode
#include "base/process/launch.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iterator>
#include <limits>
#include <set>
#include "base/allocator/type_profiler_control.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/file_util.h"
#include "base/files/dir_reader_posix.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/posix/eintr_wrapper.h"
#include "base/process/kill.h"
#include "base/process/process_metrics.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#if defined(OS_CHROMEOS)
#include <sys/ioctl.h>
#endif
#if defined(OS_FREEBSD)
#include <sys/event.h>
#include <sys/ucontext.h>
#endif
#if defined(OS_MACOSX)
#include <crt_externs.h>
#include <sys/event.h>
#else
extern char** environ;
#endif
namespace base {
namespace {
char** GetEnvironment() {
#if defined(OS_MACOSX)
return *_NSGetEnviron();
#else
return environ;
#endif
}
void SetEnvironment(char** env) {
#if defined(OS_MACOSX)
*_NSGetEnviron() = env;
#else
environ = env;
#endif
}
sigset_t SetSignalMask(const sigset_t& new_sigmask) {
sigset_t old_sigmask;
#if defined(OS_ANDROID)
RAW_CHECK(sigprocmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
#else
RAW_CHECK(pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
#endif
return old_sigmask;
}
#if !defined(OS_LINUX) || \
(!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
void ResetChildSignalHandlersToDefaults() {
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGILL, SIG_DFL);
signal(SIGABRT, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGBUS, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGSYS, SIG_DFL);
signal(SIGTERM, SIG_DFL);
}
#else
typedef uint64_t kernel_sigset_t;
struct kernel_sigaction {
void* k_sa_handler;
unsigned long k_sa_flags;
void* k_sa_restorer;
kernel_sigset_t k_sa_mask;
};
int sys_rt_sigaction(int sig, const struct kernel_sigaction* act,
struct kernel_sigaction* oact) {
return syscall(SYS_rt_sigaction, sig, act, oact, sizeof(kernel_sigset_t));
}
void ResetChildSignalHandlersToDefaults(void) {
for (int signum = 1; ; ++signum) {
struct kernel_sigaction act = {0};
int sigaction_get_ret = sys_rt_sigaction(signum, NULL, &act);
if (sigaction_get_ret && errno == EINVAL) {
#if !defined(NDEBUG)
const int kNumberOfSignals = 64;
RAW_CHECK(signum == kNumberOfSignals + 1);
#endif
break;
}
if (sigaction_get_ret) {
RAW_LOG(FATAL, "sigaction (get) failed.");
}
if (signum != SIGSTOP && signum != SIGKILL) {
act.k_sa_handler = reinterpret_cast<void*>(SIG_DFL);
act.k_sa_restorer = NULL;
if (sys_rt_sigaction(signum, &act, NULL)) {
RAW_LOG(FATAL, "sigaction (set) failed.");
}
}
#if !defined(NDEBUG)
if (sys_rt_sigaction(signum, NULL, &act) || act.k_sa_restorer) {
RAW_LOG(FATAL, "Cound not fix sa_restorer.");
}
#endif
}
}
#endif
}
struct ScopedDIRClose {
inline void operator()(DIR* x) const {
if (x)
closedir(x);
}
};
typedef scoped_ptr<DIR, ScopedDIRClose> ScopedDIR;
#if defined(OS_LINUX)
static const char kFDDir[] = "/proc/self/fd";
#elif defined(OS_MACOSX)
static const char kFDDir[] = "/dev/fd";
#elif defined(OS_SOLARIS)
static const char kFDDir[] = "/dev/fd";
#elif defined(OS_FREEBSD)
static const char kFDDir[] = "/dev/fd";
#elif defined(OS_OPENBSD)
static const char kFDDir[] = "/dev/fd";
#elif defined(OS_ANDROID)
static const char kFDDir[] = "/proc/self/fd";
#endif
void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
size_t max_fds = GetMaxFds();
DirReaderPosix fd_dir(kFDDir);
if (!fd_dir.IsValid()) {
for (size_t i = 0; i < max_fds; ++i) {
const int fd = static_cast<int>(i);
if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
continue;
size_t j;
for (j = 0; j < saved_mapping.size(); j++) {
if (fd == saved_mapping[j].dest)
break;
}
if (j < saved_mapping.size())
continue;
close(fd);
}
return;
}
const int dir_fd = fd_dir.fd();
for ( ; fd_dir.Next(); ) {
if (fd_dir.name()[0] == '.')
continue;
char *endptr;
errno = 0;
const long int fd = strtol(fd_dir.name(), &endptr, 10);
if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
continue;
if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
continue;
size_t i;
for (i = 0; i < saved_mapping.size(); i++) {
if (fd == saved_mapping[i].dest)
break;
}
if (i < saved_mapping.size())
continue;
if (fd == dir_fd)
continue;
if (fd < static_cast<int>(max_fds)) {
int ret = IGNORE_EINTR(close(fd));
DPCHECK(ret == 0);
}
}
}
bool LaunchProcess(const std::vector<std::string>& argv,
const LaunchOptions& options,
ProcessHandle* process_handle) {
size_t fd_shuffle_size = 0;
if (options.fds_to_remap) {
fd_shuffle_size = options.fds_to_remap->size();
}
InjectiveMultimap fd_shuffle1;
InjectiveMultimap fd_shuffle2;
fd_shuffle1.reserve(fd_shuffle_size);
fd_shuffle2.reserve(fd_shuffle_size);
scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
scoped_ptr<char*[]> new_environ;
if (!options.environ.empty())
new_environ = AlterEnvironment(GetEnvironment(), options.environ);
sigset_t full_sigset;
sigfillset(&full_sigset);
const sigset_t orig_sigmask = SetSignalMask(full_sigset);
pid_t pid;
#if defined(OS_LINUX)
if (options.clone_flags) {
RAW_CHECK(
!(options.clone_flags & (CLONE_SIGHAND | CLONE_THREAD | CLONE_VM)));
pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
} else
#endif
{
pid = fork();
}
if (pid != 0) {
SetSignalMask(orig_sigmask);
}
if (pid < 0) {
DPLOG(ERROR) << "fork";
return false;
} else if (pid == 0) {
base::ScopedFD null_fd(HANDLE_EINTR(open("/dev/null", O_RDONLY)));
if (!null_fd.is_valid()) {
RAW_LOG(ERROR, "Failed to open /dev/null");
_exit(127);
}
int new_fd = HANDLE_EINTR(dup2(null_fd.get(), STDIN_FILENO));
if (new_fd != STDIN_FILENO) {
RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
_exit(127);
}
if (options.new_process_group) {
if (setpgid(0, 0) < 0) {
RAW_LOG(ERROR, "setpgid failed");
_exit(127);
}
}
base::type_profiler::Controller::Stop();
if (options.maximize_rlimits) {
for (size_t i = 0; i < options.maximize_rlimits->size(); ++i) {
const int resource = (*options.maximize_rlimits)[i];
struct rlimit limit;
if (getrlimit(resource, &limit) < 0) {
RAW_LOG(WARNING, "getrlimit failed");
} else if (limit.rlim_cur < limit.rlim_max) {
limit.rlim_cur = limit.rlim_max;
if (setrlimit(resource, &limit) < 0) {
RAW_LOG(WARNING, "setrlimit failed");
}
}
}
}
#if defined(OS_MACOSX)
RestoreDefaultExceptionHandler();
#endif
ResetChildSignalHandlersToDefaults();
SetSignalMask(orig_sigmask);
#if 0
void *malloc_thunk =
reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
memset(reinterpret_cast<void*>(malloc), 0xff, 8);
#endif
#if defined(OS_CHROMEOS)
if (options.ctrl_terminal_fd >= 0) {
if (HANDLE_EINTR(setsid()) != -1) {
if (HANDLE_EINTR(
ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
}
} else {
RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
}
}
#endif
if (options.fds_to_remap) {
for (size_t i = 0; i < options.fds_to_remap->size(); ++i) {
const FileHandleMappingVector::value_type& value =
(*options.fds_to_remap)[i];
fd_shuffle1.push_back(InjectionArc(value.first, value.second, false));
fd_shuffle2.push_back(InjectionArc(value.first, value.second, false));
}
}
if (!options.environ.empty())
SetEnvironment(new_environ.get());
if (!ShuffleFileDescriptors(&fd_shuffle1))
_exit(127);
CloseSuperfluousFds(fd_shuffle2);
for (size_t i = 0; i < argv.size(); i++)
argv_cstr[i] = const_cast<char*>(argv[i].c_str());
argv_cstr[argv.size()] = NULL;
execvp(argv_cstr[0], argv_cstr.get());
RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
RAW_LOG(ERROR, argv_cstr[0]);
_exit(127);
} else {
if (options.wait) {
base::ThreadRestrictions::AssertIOAllowed();
pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
DPCHECK(ret > 0);
}
if (process_handle)
*process_handle = pid;
}
return true;
}
bool LaunchProcess(const CommandLine& cmdline,
const LaunchOptions& options,
ProcessHandle* process_handle) {
return LaunchProcess(cmdline.argv(), options, process_handle);
}
void RaiseProcessToHighPriority() {
}
enum GetAppOutputInternalResult {
EXECUTE_FAILURE,
EXECUTE_SUCCESS,
GOT_MAX_OUTPUT,
};
static GetAppOutputInternalResult GetAppOutputInternal(
const std::vector<std::string>& argv,
char* const envp[],
std::string* output,
size_t max_output,
bool do_search_path,
int* exit_code) {
base::ThreadRestrictions::AssertIOAllowed();
DCHECK(exit_code);
*exit_code = EXIT_FAILURE;
int pipe_fd[2];
pid_t pid;
InjectiveMultimap fd_shuffle1, fd_shuffle2;
scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
fd_shuffle1.reserve(3);
fd_shuffle2.reserve(3);
DCHECK(!do_search_path ^ !envp);
if (pipe(pipe_fd) < 0)
return EXECUTE_FAILURE;
switch (pid = fork()) {
case -1:
close(pipe_fd[0]);
close(pipe_fd[1]);
return EXECUTE_FAILURE;
case 0:
{
#if defined(OS_MACOSX)
RestoreDefaultExceptionHandler();
#endif
int dev_null = open("/dev/null", O_WRONLY);
if (dev_null < 0)
_exit(127);
base::type_profiler::Controller::Stop();
fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
for (size_t i = 0; i < fd_shuffle1.size(); ++i)
fd_shuffle2.push_back(fd_shuffle1[i]);
if (!ShuffleFileDescriptors(&fd_shuffle1))
_exit(127);
CloseSuperfluousFds(fd_shuffle2);
for (size_t i = 0; i < argv.size(); i++)
argv_cstr[i] = const_cast<char*>(argv[i].c_str());
argv_cstr[argv.size()] = NULL;
if (do_search_path)
execvp(argv_cstr[0], argv_cstr.get());
else
execve(argv_cstr[0], argv_cstr.get(), envp);
_exit(127);
}
default:
{
close(pipe_fd[1]);
output->clear();
char buffer[256];
size_t output_buf_left = max_output;
ssize_t bytes_read = 1;
while (output_buf_left > 0) {
bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
std::min(output_buf_left, sizeof(buffer))));
if (bytes_read <= 0)
break;
output->append(buffer, bytes_read);
output_buf_left -= static_cast<size_t>(bytes_read);
}
close(pipe_fd[0]);
bool success = WaitForExitCode(pid, exit_code);
if (!output_buf_left && bytes_read > 0)
return GOT_MAX_OUTPUT;
else if (success)
return EXECUTE_SUCCESS;
return EXECUTE_FAILURE;
}
}
}
bool GetAppOutput(const CommandLine& cl, std::string* output) {
return GetAppOutput(cl.argv(), output);
}
bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
int exit_code;
GetAppOutputInternalResult result = GetAppOutputInternal(
argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
&exit_code);
return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
}
bool GetAppOutputRestricted(const CommandLine& cl,
std::string* output, size_t max_output) {
char* const empty_environ = NULL;
int exit_code;
GetAppOutputInternalResult result = GetAppOutputInternal(
cl.argv(), &empty_environ, output, max_output, false, &exit_code);
return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
exit_code == EXIT_SUCCESS);
}
bool GetAppOutputWithExitCode(const CommandLine& cl,
std::string* output,
int* exit_code) {
GetAppOutputInternalResult result = GetAppOutputInternal(
cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
exit_code);
return result == EXECUTE_SUCCESS;
}
}