Move some parts of ProcessReader (in snapshot) to ProcessInfo (in util).

Also, move ProcessArgumentsForPID() into ProcessInfo.

This change prepares for a TaskForPID() implementation that’s capable of
operating correctly in a setuid root executable. TaskForPID() belongs in
util/mach, but for its permission checks, it must access some process
properties that were previously fetched by ProcessReader in snapshot.
util can’t depend on snapshot. The generic util-safe process information
bits (Is64Bit(), ProcessID(), ParentProcessID(), and StartTime()) are
moved from ProcessReader to ProcessInfo (in util), where the current
ProcessReader can use it (as it’s OK for snapshot to depend on util),
and the future TaskForPID() in util can also use it. ProcessInfo also
contains other methods that TaskForPID() will use, providing access to
the credentials that the target process holds. ProcessArgumentsForPID()
is related, and is also now a part of ProcessInfo.

TEST=snapshot_test, util_test
R=rsesek@chromium.org

Review URL: https://codereview.chromium.org/727973002
This commit is contained in:
Mark Mentovai 2014-11-14 17:54:42 -05:00
parent 360e441c53
commit 6812cec67e
10 changed files with 561 additions and 229 deletions

View File

@ -90,7 +90,7 @@ ProcessReader::Module::~Module() {
}
ProcessReader::ProcessReader()
: kern_proc_info_(),
: process_info_(),
threads_(),
modules_(),
module_readers_(),
@ -112,23 +112,11 @@ ProcessReader::~ProcessReader() {
bool ProcessReader::Initialize(task_t task) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
pid_t pid;
kern_return_t kr = pid_for_task(task, &pid);
if (kr != KERN_SUCCESS) {
MACH_LOG(ERROR, kr) << "pid_for_task";
if (!process_info_.InitializeFromTask(task)) {
return false;
}
int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
size_t len = sizeof(kern_proc_info_);
if (sysctl(mib, arraysize(mib), &kern_proc_info_, &len, nullptr, 0) != 0) {
PLOG(ERROR) << "sysctl for pid " << pid;
return false;
}
DCHECK_EQ(kern_proc_info_.kp_proc.p_pid, pid);
is_64_bit_ = kern_proc_info_.kp_proc.p_flag & P_LP64;
is_64_bit_ = process_info_.Is64Bit();
task_memory_.reset(new TaskMemory(task));
task_ = task;
@ -137,11 +125,6 @@ bool ProcessReader::Initialize(task_t task) {
return true;
}
void ProcessReader::StartTime(timeval* start_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*start_time = kern_proc_info_.kp_proc.p_starttime;
}
bool ProcessReader::CPUTimes(timeval* user_time, timeval* system_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);

View File

@ -16,7 +16,6 @@
#define CRASHPAD_SNAPSHOT_MAC_PROCESS_READER_H_
#include <mach/mach.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
@ -29,6 +28,7 @@
#include "build/build_config.h"
#include "util/mach/task_memory.h"
#include "util/misc/initialization_state_dcheck.h"
#include "util/posix/process_info.h"
#include "util/stdlib/pointer_container.h"
namespace crashpad {
@ -112,14 +112,20 @@ class ProcessReader {
bool Is64Bit() const { return is_64_bit_; }
//! \return The target tasks process ID.
pid_t ProcessID() const { return kern_proc_info_.kp_proc.p_pid; }
pid_t ProcessID() const { return process_info_.ProcessID(); }
//! \return The target tasks parent process ID.
pid_t ParentProcessID() const { return kern_proc_info_.kp_eproc.e_ppid; }
pid_t ParentProcessID() const { return process_info_.ParentProcessID(); }
//! \brief Determines the target process start time.
//!
//! \param[out] start_time The time that the process started.
void StartTime(timeval* start_time) const;
void StartTime(timeval* start_time) const {
process_info_.StartTime(start_time);
}
//! \brief Determines the target process execution time.
//!
//! \param[out] user_time The amount of time the process has executed code in
//! user mode.
//! \param[out] system_time The amount of time the process has executed code
@ -206,7 +212,7 @@ class ProcessReader {
mach_vm_address_t* region_size,
unsigned int user_tag);
kinfo_proc kern_proc_info_;
ProcessInfo process_info_;
std::vector<Thread> threads_; // owns send rights
std::vector<Module> modules_;
PointerVector<MachOImageReader> module_readers_;
@ -214,8 +220,9 @@ class ProcessReader {
task_t task_; // weak
InitializationStateDcheck initialized_;
// This shadows a bit in kern_proc_info_, but its accessed so frequently that
// its given a first-class field to save a few bit operations on each access.
// This shadows a method of process_info_, but its accessed so frequently
// that its given a first-class field to save a call and a few bit operations
// on each access.
bool is_64_bit_;
bool initialized_threads_;

View File

@ -27,7 +27,7 @@
#include "base/rand_util.h"
#include "gtest/gtest.h"
#include "util/misc/clock.h"
#include "util/posix/process_util.h"
#include "util/posix/process_info.h"
#include "util/stdlib/objc.h"
namespace crashpad {
@ -37,18 +37,21 @@ namespace {
// Ensures that the process with the specified PID is running, identifying it by
// requiring that its argv[argc - 1] compare equal to last_arg.
void ExpectProcessIsRunning(pid_t pid, std::string& last_arg) {
ProcessInfo process_info;
ASSERT_TRUE(process_info.Initialize(pid));
// The process may not have called exec yet, so loop with a small delay while
// looking for the cookie.
int outer_tries = 10;
std::vector<std::string> job_argv;
while (outer_tries--) {
// If the process is in the middle of calling exec, ProcessArgumentsForPID
// If the process is in the middle of calling exec, process_info.Arguments()
// may fail. Loop with a small retry delay while waiting for the expected
// successful call.
int inner_tries = 10;
bool success;
do {
success = ProcessArgumentsForPID(pid, &job_argv);
success = process_info.Arguments(&job_argv);
if (success) {
break;
}
@ -81,7 +84,8 @@ void ExpectProcessIsNotRunning(pid_t pid, std::string& last_arg) {
int tries = 10;
std::vector<std::string> job_argv;
while (tries--) {
if (!ProcessArgumentsForPID(pid, &job_argv)) {
ProcessInfo process_info;
if (!process_info.Initialize(pid) || !process_info.Arguments(&job_argv)) {
// The PID was not found.
return;
}

152
util/posix/process_info.h Normal file
View File

@ -0,0 +1,152 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_UTIL_POSIX_PROCESS_INFO_H_
#define CRASHPAD_UTIL_POSIX_PROCESS_INFO_H_
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <set>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "build/build_config.h"
#include "util/misc/initialization_state_dcheck.h"
#if defined(OS_MACOSX)
#include <mach/mach.h>
#endif
namespace crashpad {
class ProcessInfo {
public:
ProcessInfo();
~ProcessInfo();
//! \brief Initializes this object with information about the process whose ID
//! is \a pid.
//!
//! This method must be called successfully prior to calling any other method
//! in this class. This method may only be called once.
//!
//! It is unspecified whether the information that an object of this class
//! returns is loaded at the time Initialize() is called or subsequently, and
//! whether this information is cached in the object or not.
//!
//! \param[in] pid The process ID to obtain information for.
//!
//! \return `true` on success, `false` on failure with a message logged.
bool Initialize(pid_t pid);
#if defined(OS_MACOSX) || DOXYGEN
//! \brief Initializes this object with information about a process based on
//! its Mach task.
//!
//! This method serves as a stand-in for Initialize() and may be called in its
//! place with the same restrictions and considerations.
//!
//! \param[in] task The Mach task to obtain information for.
//!
//! \return `true` on success, `false` on failure with an message logged.
bool InitializeFromTask(task_t task);
#endif
//! \return The target tasks process ID.
pid_t ProcessID() const;
//! \return The target tasks parent process ID.
pid_t ParentProcessID() const;
//! \return The target process real user ID as would be returned to it by
//! `getuid()`.
uid_t RealUserID() const;
//! \return The target process effective user ID as would be returned to it
//! by `geteuid()`.
uid_t EffectiveUserID() const;
//! \return The target process saved set-user ID.
uid_t SavedUserID() const;
//! \return the target process real group ID as would be returned to it by
//! `getgid()`.
gid_t RealGroupID() const;
//! \return the target process effective group ID as would be returned to it
//! by `getegid()`.
gid_t EffectiveGroupID() const;
//! \return The target process saved set-group ID.
gid_t SavedGroupID() const;
//! \return the target process supplementary group list as would be returned
//! to it by `getgroups()`.
std::set<gid_t> SupplementaryGroups() const;
//! \return All groups that the target process claims membership in, including
//! RealGroupID(), EffectiveGroupID(), SavedGroupID(), and
//! SupplementaryGroups().
std::set<gid_t> AllGroups() const;
//! \brief Determines whether the target process has changed privileges.
//!
//! A process is considered to have changed privileges if it has changed its
//! real, effective, or saved set-user or group IDs with the `setuid()`,
//! `seteuid()`, `setreuid()`, `setgid()`, `setegid()`, or `setregid()` system
//! calls since its most recent `execve()`, or if its privileges changed at
//! `execve()` as a result of executing a setuid or setgid executable.
bool DidChangePrivileges() const;
//! \return `true` if the target task is a 64-bit process.
bool Is64Bit() const;
//! \brief Determines the target process start time.
//!
//! \param[out] start_time The time that the process started.
void StartTime(timeval* start_time) const;
//! \brief Obtains the arguments used to launch a process.
//!
//! Whether it is possible to obtain this information for a process with
//! different privileges than the running program is system-dependent.
//!
//! \param[out] argv The process arguments as passed to its `main()` function
//! as the \a argv parameter, possibly modified by the process.
//!
//! \return `true` on success, with \a argv populated appropriately.
//! Otherwise, `false` with a message logged.
//!
//! \note This function may spuriously return `false` when used to examine a
//! process that it is calling `exec()`. If examining such a process, call
//! this function in a retry loop with a small (100ns) delay to avoid an
//! erroneous assumption that \a pid is not running.
bool Arguments(std::vector<std::string>* argv) const;
private:
#if defined(OS_MACOSX)
kinfo_proc kern_proc_info_;
#endif
InitializationStateDcheck initialized_;
DISALLOW_COPY_AND_ASSIGN(ProcessInfo);
};
} // namespace crashpad
#endif // CRASHPAD_UTIL_POSIX_PROCESS_INFO_H_

View File

@ -0,0 +1,233 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/posix/process_info.h"
#include <string.h>
#include "base/logging.h"
#include "base/mac/mach_logging.h"
namespace crashpad {
ProcessInfo::ProcessInfo() : kern_proc_info_(), initialized_() {
}
ProcessInfo::~ProcessInfo() {
}
bool ProcessInfo::Initialize(pid_t pid) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
size_t len = sizeof(kern_proc_info_);
if (sysctl(mib, arraysize(mib), &kern_proc_info_, &len, nullptr, 0) != 0) {
PLOG(ERROR) << "sysctl for pid " << pid;
return false;
}
// This sysctl does not return an error if the pid was not found. 10.9.5
// xnu-2422.115.4/bsd/kern/kern_sysctl.c sysctl_prochandle() calls
// xnu-2422.115.4/bsd/kern/kern_proc.c proc_iterate(), which provides no
// indication of whether anything was done. To catch this, check that the PID
// has changed from the 0 value it was given when initialized by the
// constructor.
if (kern_proc_info_.kp_proc.p_pid == 0) {
LOG(WARNING) << "pid " << pid << " not found";
return false;
}
DCHECK_EQ(kern_proc_info_.kp_proc.p_pid, pid);
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
bool ProcessInfo::InitializeFromTask(task_t task) {
pid_t pid;
kern_return_t kr = pid_for_task(task, &pid);
if (kr != KERN_SUCCESS) {
MACH_LOG(ERROR, kr) << "pid_for_task";
return false;
}
return Initialize(pid);
}
pid_t ProcessInfo::ProcessID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_proc.p_pid;
}
pid_t ProcessInfo::ParentProcessID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_ppid;
}
uid_t ProcessInfo::RealUserID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_pcred.p_ruid;
}
uid_t ProcessInfo::EffectiveUserID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_ucred.cr_uid;
}
uid_t ProcessInfo::SavedUserID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_pcred.p_svuid;
}
gid_t ProcessInfo::RealGroupID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_pcred.p_rgid;
}
gid_t ProcessInfo::EffectiveGroupID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_ucred.cr_gid;
}
gid_t ProcessInfo::SavedGroupID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_eproc.e_pcred.p_svgid;
}
std::set<gid_t> ProcessInfo::SupplementaryGroups() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
const short ngroups = kern_proc_info_.kp_eproc.e_ucred.cr_ngroups;
DCHECK_GE(ngroups, 0);
DCHECK_LT(static_cast<size_t>(ngroups),
arraysize(kern_proc_info_.kp_eproc.e_ucred.cr_groups));
const gid_t* groups = kern_proc_info_.kp_eproc.e_ucred.cr_groups;
return std::set<gid_t>(&groups[0], &groups[ngroups]);
}
std::set<gid_t> ProcessInfo::AllGroups() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
std::set<gid_t> all_groups = SupplementaryGroups();
all_groups.insert(RealGroupID());
all_groups.insert(EffectiveGroupID());
all_groups.insert(SavedGroupID());
return all_groups;
}
bool ProcessInfo::DidChangePrivileges() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_proc.p_flag & P_SUGID;
}
bool ProcessInfo::Is64Bit() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return kern_proc_info_.kp_proc.p_flag & P_LP64;
}
void ProcessInfo::StartTime(timeval* start_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*start_time = kern_proc_info_.kp_proc.p_starttime;
}
bool ProcessInfo::Arguments(std::vector<std::string>* argv) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
// The format of KERN_PROCARGS2 is explained in 10.9.2 adv_cmds-153/ps/print.c
// getproclline(). It is an int (argc) followed by the executables string
// area. The string area consists of NUL-terminated strings, beginning with
// the executable path, and then starting on an aligned boundary, all of the
// elements of argv, envp, and applev.
// It is possible for a process to exec() in between the two sysctl() calls
// below. If that happens, and the string area of the new program is larger
// than that of the old one, args_size_estimate will be too small. To detect
// this situation, the second sysctl() attempts to fetch args_size_estimate +
// 1 bytes, expecting to only receive args_size_estimate. If it gets the extra
// byte, it indicates that the string area has grown, and the sysctl() pair
// will be retried a limited number of times.
size_t args_size_estimate;
size_t args_size;
std::string args;
int tries = 3;
const pid_t pid = ProcessID();
do {
int mib[] = {CTL_KERN, KERN_PROCARGS2, pid};
int rv =
sysctl(mib, arraysize(mib), nullptr, &args_size_estimate, nullptr, 0);
if (rv != 0) {
PLOG(ERROR) << "sysctl (size) for pid " << pid;
return false;
}
args_size = args_size_estimate + 1;
args.resize(args_size);
rv = sysctl(mib, arraysize(mib), &args[0], &args_size, nullptr, 0);
if (rv != 0) {
PLOG(ERROR) << "sysctl (data) for pid " << pid;
return false;
}
} while (args_size == args_size_estimate + 1 && tries--);
if (args_size == args_size_estimate + 1) {
LOG(ERROR) << "unexpected args_size";
return false;
}
// KERN_PROCARGS2 needs to at least contain argc.
if (args_size < sizeof(int)) {
LOG(ERROR) << "tiny args_size";
return false;
}
args.resize(args_size);
// Get argc.
int argc;
memcpy(&argc, &args[0], sizeof(argc));
// Find the end of the executable path.
size_t start_pos = sizeof(argc);
size_t nul_pos = args.find('\0', start_pos);
if (nul_pos == std::string::npos) {
LOG(ERROR) << "unterminated executable path";
return false;
}
// Find the beginning of the string area.
start_pos = args.find_first_not_of('\0', nul_pos);
if (start_pos == std::string::npos) {
LOG(ERROR) << "no string area";
return false;
}
std::vector<std::string> local_argv;
while (argc-- && nul_pos != std::string::npos) {
nul_pos = args.find('\0', start_pos);
local_argv.push_back(args.substr(start_pos, nul_pos - start_pos));
start_pos = nul_pos + 1;
}
if (argc >= 0) {
// Not every argument was recovered.
LOG(ERROR) << "did not recover all arguments";
return false;
}
argv->swap(local_argv);
return true;
}
} // namespace crashpad

View File

@ -0,0 +1,148 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/posix/process_info.h"
#include <time.h>
#include <unistd.h>
#include <set>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "util/test/errors.h"
#if defined(OS_MACOSX)
#include <crt_externs.h>
#endif
namespace crashpad {
namespace test {
namespace {
void TestSelfProcess(const ProcessInfo& process_info) {
EXPECT_EQ(getpid(), process_info.ProcessID());
EXPECT_EQ(getppid(), process_info.ParentProcessID());
// Theres no system call to obtain the saved set-user ID or saved set-group
// ID in an easy way. Normally, they are the same as the effective user ID and
// effective group ID, so just check against those.
EXPECT_EQ(getuid(), process_info.RealUserID());
const uid_t euid = geteuid();
EXPECT_EQ(euid, process_info.EffectiveUserID());
EXPECT_EQ(euid, process_info.SavedUserID());
const gid_t gid = getgid();
EXPECT_EQ(gid, process_info.RealGroupID());
const gid_t egid = getegid();
EXPECT_EQ(egid, process_info.EffectiveGroupID());
EXPECT_EQ(egid, process_info.SavedGroupID());
// Test SupplementaryGroups().
int group_count = getgroups(0, nullptr);
ASSERT_GE(group_count, 0) << ErrnoMessage("getgroups");
std::vector<gid_t> group_vector(group_count);
if (group_count > 0) {
group_count = getgroups(group_vector.size(), &group_vector[0]);
ASSERT_GE(group_count, 0) << ErrnoMessage("getgroups");
ASSERT_EQ(group_vector.size(), implicit_cast<size_t>(group_count));
}
std::set<gid_t> group_set(group_vector.begin(), group_vector.end());
EXPECT_EQ(group_set, process_info.SupplementaryGroups());
// Test AllGroups(), which is SupplementaryGroups() plus the real, effective,
// and saved set-group IDs. The effective and saved set-group IDs are expected
// to be identical (see above).
group_set.insert(gid);
group_set.insert(egid);
EXPECT_EQ(group_set, process_info.AllGroups());
// The test executable isnt expected to change privileges.
EXPECT_FALSE(process_info.DidChangePrivileges());
#if defined(ARCH_CPU_64_BITS)
EXPECT_TRUE(process_info.Is64Bit());
#else
EXPECT_FALSE(process_info.Is64Bit());
#endif
// Test StartTime(). This program must have started at some time in the past.
timeval start_time;
process_info.StartTime(&start_time);
time_t now;
time(&now);
EXPECT_LE(start_time.tv_sec, now);
std::vector<std::string> argv;
ASSERT_TRUE(process_info.Arguments(&argv));
// gtest argv processing scrambles argv, but it leaves argc and argv[0]
// intact, so test those.
#if defined(OS_MACOSX)
int expect_argc = *_NSGetArgc();
char** expect_argv = *_NSGetArgv();
#else
#error Obtain expect_argc and expect_argv correctly on your system.
#endif
int argc = implicit_cast<int>(argv.size());
EXPECT_EQ(expect_argc, argc);
ASSERT_GE(expect_argc, 1);
ASSERT_GE(argc, 1);
EXPECT_EQ(std::string(expect_argv[0]), argv[0]);
}
TEST(ProcessInfo, Self) {
ProcessInfo process_info;
ASSERT_TRUE(process_info.Initialize(getpid()));
TestSelfProcess(process_info);
}
#if defined(OS_MACOSX)
TEST(ProcessInfo, SelfTask) {
ProcessInfo process_info;
ASSERT_TRUE(process_info.InitializeFromTask(mach_task_self()));
TestSelfProcess(process_info);
}
#endif
TEST(ProcessInfo, Pid1) {
// PID 1 is expected to be init or the systems equivalent. This tests reading
// information about another process.
ProcessInfo process_info;
ASSERT_TRUE(process_info.Initialize(1));
EXPECT_EQ(implicit_cast<pid_t>(1), process_info.ProcessID());
EXPECT_EQ(implicit_cast<pid_t>(0), process_info.ParentProcessID());
EXPECT_EQ(implicit_cast<uid_t>(0), process_info.RealUserID());
EXPECT_EQ(implicit_cast<uid_t>(0), process_info.EffectiveUserID());
EXPECT_EQ(implicit_cast<uid_t>(0), process_info.SavedUserID());
EXPECT_EQ(implicit_cast<gid_t>(0), process_info.RealGroupID());
EXPECT_EQ(implicit_cast<gid_t>(0), process_info.EffectiveGroupID());
EXPECT_EQ(implicit_cast<gid_t>(0), process_info.SavedGroupID());
EXPECT_FALSE(process_info.AllGroups().empty());
}
} // namespace
} // namespace test
} // namespace crashpad

View File

@ -1,42 +0,0 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_UTIL_POSIX_PROCESS_UTIL_POSIX_H_
#define CRASHPAD_UTIL_POSIX_PROCESS_UTIL_POSIX_H_
#include <unistd.h>
#include <string>
#include <vector>
namespace crashpad {
//! \brief Obtains the arguments used to launch a process.
//!
//! \param[in] pid The process ID of the process to examine.
//! \param[out] argv The process arguments as passed to its `main()` function
//! as the \a argv parameter, possibly modified by the process.
//!
//! \return `true` on success, with \a argv populated appropriately. Otherwise,
//! `false`.
//!
//! \note This function may spuriously return `false` when used to examine a
//! process that it is calling `exec()`. If examining such a process, call
//! this function in a retry loop with a small (100ns) delay to avoid an
//! erroneous assumption that \a pid is not running.
bool ProcessArgumentsForPID(pid_t pid, std::vector<std::string>* argv);
} // namespace crashpad
#endif // CRASHPAD_UTIL_POSIX_PROCESS_UTIL_POSIX_H_

View File

@ -1,103 +0,0 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/posix/process_util.h"
#include <string.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include "base/basictypes.h"
namespace crashpad {
bool ProcessArgumentsForPID(pid_t pid, std::vector<std::string>* argv) {
// The format of KERN_PROCARGS2 is explained in 10.9.2 adv_cmds-153/ps/print.c
// getproclline(). It is an int (argc) followed by the executables string
// area. The string area consists of NUL-terminated strings, beginning with
// the executable path, and then starting on an aligned boundary, all of the
// elements of argv, envp, and applev.
// It is possible for a process to exec() in between the two sysctl() calls
// below. If that happens, and the string area of the new program is larger
// than that of the old one, args_size_estimate will be too small. To detect
// this situation, the second sysctl() attempts to fetch args_size_estimate +
// 1 bytes, expecting to only receive args_size_estimate. If it gets the extra
// byte, it indicates that the string area has grown, and the sysctl() pair
// will be retried a limited number of times.
size_t args_size_estimate;
size_t args_size;
std::string args;
int tries = 3;
do {
int mib[] = {CTL_KERN, KERN_PROCARGS2, pid};
int rv =
sysctl(mib, arraysize(mib), nullptr, &args_size_estimate, nullptr, 0);
if (rv != 0) {
return false;
}
args_size = args_size_estimate + 1;
args.resize(args_size);
rv = sysctl(mib, arraysize(mib), &args[0], &args_size, nullptr, 0);
if (rv != 0) {
return false;
}
} while (args_size == args_size_estimate + 1 && tries--);
if (args_size == args_size_estimate + 1) {
return false;
}
// KERN_PROCARGS2 needs to at least contain argc.
if (args_size < sizeof(int)) {
return false;
}
args.resize(args_size);
// Get argc.
int argc;
memcpy(&argc, &args[0], sizeof(argc));
// Find the end of the executable path.
size_t start_pos = sizeof(argc);
size_t nul_pos = args.find('\0', start_pos);
if (nul_pos == std::string::npos) {
return false;
}
// Find the beginning of the string area.
start_pos = args.find_first_not_of('\0', nul_pos);
if (start_pos == std::string::npos) {
return false;
}
std::vector<std::string> local_argv;
while (argc-- && nul_pos != std::string::npos) {
nul_pos = args.find('\0', start_pos);
local_argv.push_back(args.substr(start_pos, nul_pos - start_pos));
start_pos = nul_pos + 1;
}
if (argc >= 0) {
// Not every argument was recovered.
return false;
}
argv->swap(local_argv);
return true;
}
} // namespace crashpad

View File

@ -1,50 +0,0 @@
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/posix/process_util.h"
#include <crt_externs.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "gtest/gtest.h"
namespace crashpad {
namespace test {
namespace {
TEST(ProcessUtil, ProcessArgumentsForPID) {
std::vector<std::string> argv;
ASSERT_TRUE(ProcessArgumentsForPID(getpid(), &argv));
// gtest argv processing scrambles argv, but it leaves argc and argv[0]
// intact, so test those.
int argc = implicit_cast<int>(argv.size());
int expect_argc = *_NSGetArgc();
EXPECT_EQ(expect_argc, argc);
ASSERT_GE(expect_argc, 1);
ASSERT_GE(argc, 1);
char** expect_argv = *_NSGetArgv();
EXPECT_EQ(std::string(expect_argv[0]), argv[0]);
}
} // namespace
} // namespace test
} // namespace crashpad

View File

@ -82,8 +82,8 @@
'numeric/in_range_cast.h',
'numeric/int128.h',
'numeric/safe_assignment.h',
'posix/process_util.h',
'posix/process_util_mac.cc',
'posix/process_info.h',
'posix/process_info_mac.cc',
'posix/symbolic_constants_posix.cc',
'posix/symbolic_constants_posix.h',
'stdlib/cxx.h',
@ -229,7 +229,7 @@
'numeric/checked_range_test.cc',
'numeric/in_range_cast_test.cc',
'numeric/int128_test.cc',
'posix/process_util_test.cc',
'posix/process_info_test.cc',
'posix/symbolic_constants_posix_test.cc',
'stdlib/string_number_conversion_test.cc',
'stdlib/strlcpy_test.cc',