Commit 92f88884 authored by Scott Graham's avatar Scott Graham Committed by Commit Bot

Update Crashpad to 0924e567514fc577e725b56cd602808467b317a9

c04c05564db1 linux: Fix gcc -Wparentheses error from 7a0daa6989a9
92e8bc4713e1 win: Fix ProcessInfo.OtherProcess test flake
0cc63d4a4558 android: Make run_tests.py work on Android versions before
             7.0 (N)
13d0defbfb45 android, win: Enable colored test output when available
0924e567514f linux: Add PtraceBroker and PtraceClient

Re-enables ProcessInfo.OtherProcess.

Bug: chromium:792619
Change-Id: Ic1178674e6704b9c4560be52a9197c53930a5a9b
Reviewed-on: https://chromium-review.googlesource.com/823218Reviewed-by: default avatarMark Mentovai <mark@chromium.org>
Commit-Queue: Scott Graham <scottmg@chromium.org>
Cr-Commit-Position: refs/heads/master@{#523617}
parent 6c1d127a
......@@ -2,7 +2,7 @@ Name: Crashpad
Short Name: crashpad
URL: https://crashpad.chromium.org/
Version: unknown
Revision: ac3cc1b884e0f91d189618f69bafee40c64967b0
Revision: 0924e567514fc577e725b56cd602808467b317a9
License: Apache 2.0
License File: crashpad/LICENSE
Security Critical: yes
......@@ -36,5 +36,3 @@ $ git am --3way --message-id -p4 /tmp/patchdir
Local Modifications:
- codereview.settings has been excluded.
- ProcessInfo.OtherProcess disabled due to flake, investigation pending.
See https://crbug.com/792619.
......@@ -258,7 +258,7 @@ ElfImageReader::NoteReader::Result ElfImageReader::NoteReader::ReadNote(
current_address_ += sizeof(note_info);
constexpr size_t align = sizeof(note_info.n_namesz);
#define PAD(x) ((x) + align - 1 & ~(align - 1))
#define PAD(x) (((x) + align - 1) & ~(align - 1))
size_t padded_namesz = PAD(note_info.n_namesz);
size_t padded_descsz = PAD(note_info.n_descsz);
size_t note_size = padded_namesz + padded_descsz;
......
......@@ -35,6 +35,7 @@
#include "gtest/gtest.h"
#include "test/errors.h"
#include "test/linux/fake_ptrace_connection.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "util/file/file_io.h"
#include "util/linux/direct_ptrace_connection.h"
......@@ -49,28 +50,6 @@ pid_t gettid() {
return syscall(SYS_gettid);
}
LinuxVMAddress GetTLS() {
LinuxVMAddress tls;
#if defined(ARCH_CPU_ARMEL)
// 0xffff0fe0 is the address of the kernel user helper __kuser_get_tls().
auto kuser_get_tls = reinterpret_cast<void* (*)()>(0xffff0fe0);
tls = FromPointerCast<LinuxVMAddress>(kuser_get_tls());
#elif defined(ARCH_CPU_ARM64)
// Linux/aarch64 places the tls address in system register tpidr_el0.
asm("mrs %0, tpidr_el0" : "=r"(tls));
#elif defined(ARCH_CPU_X86)
uint32_t tls_32;
asm("movl %%gs:0x0, %0" : "=r"(tls_32));
tls = tls_32;
#elif defined(ARCH_CPU_X86_64)
asm("movq %%fs:0x0, %0" : "=r"(tls));
#else
#error Port.
#endif // ARCH_CPU_ARMEL
return tls;
}
TEST(ProcessReader, SelfBasic) {
FakePtraceConnection connection;
connection.Initialize(getpid());
......
// Copyright 2017 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 "test/linux/get_tls.h"
#include "build/build_config.h"
#include "util/misc/from_pointer_cast.h"
namespace crashpad {
namespace test {
LinuxVMAddress GetTLS() {
LinuxVMAddress tls;
#if defined(ARCH_CPU_ARMEL)
// 0xffff0fe0 is the address of the kernel user helper __kuser_get_tls().
auto kuser_get_tls = reinterpret_cast<void* (*)()>(0xffff0fe0);
tls = FromPointerCast<LinuxVMAddress>(kuser_get_tls());
#elif defined(ARCH_CPU_ARM64)
// Linux/aarch64 places the tls address in system register tpidr_el0.
asm("mrs %0, tpidr_el0" : "=r"(tls));
#elif defined(ARCH_CPU_X86)
uint32_t tls_32;
asm("movl %%gs:0x0, %0" : "=r"(tls_32));
tls = tls_32;
#elif defined(ARCH_CPU_X86_64)
asm("movq %%fs:0x0, %0" : "=r"(tls));
#else
#error Port.
#endif // ARCH_CPU_ARMEL
return tls;
}
} // namespace test
} // namespace crashpad
// Copyright 2017 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_TEST_LINUX_GET_TLS_H_
#define CRASHPAD_TEST_LINUX_GET_TLS_H_
#include "util/linux/address_types.h"
namespace crashpad {
namespace test {
//! \brief Return the thread-local storage address for the current thread.
LinuxVMAddress GetTLS();
} // namespace test
} // namespace crashpad
#endif // CRASHPAD_TEST_LINUX_GET_TLS_H_
......@@ -43,6 +43,8 @@
'hex_string.h',
'linux/fake_ptrace_connection.cc',
'linux/fake_ptrace_connection.h',
'linux/get_tls.cc',
'linux/get_tls.h',
'mac/dyld.cc',
'mac/dyld.h',
'mac/exception_swallower.cc',
......
......@@ -491,14 +491,6 @@ if (is_win) {
sources = [
"win/process_info_test_child.cc",
]
# Set an unusually high load address to make sure that the main executable
# still appears as the first element in ProcessInfo::Modules().
ldflags = [
"/BASE:0x78000000",
"/DYNAMICBASE:NO",
"/FIXED",
]
}
executable("crashpad_util_test_safe_terminate_process_test_child") {
......
......@@ -22,7 +22,7 @@ DirectPtraceConnection::DirectPtraceConnection()
: PtraceConnection(),
attachments_(),
pid_(-1),
ptracer_(),
ptracer_(/* can_log= */ true),
initialized_() {}
DirectPtraceConnection::~DirectPtraceConnection() {}
......
// Copyright 2017 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/linux/ptrace_broker.h"
#include <unistd.h>
#include "base/logging.h"
#include "util/file/file_io.h"
namespace crashpad {
PtraceBroker::PtraceBroker(int sock, bool is_64_bit)
: ptracer_(is_64_bit, /* can_log= */ false),
attachments_(nullptr),
attach_count_(0),
attach_capacity_(0),
sock_(sock) {
AllocateAttachments();
}
PtraceBroker::~PtraceBroker() = default;
int PtraceBroker::Run() {
int result = RunImpl();
ReleaseAttachments();
return result;
}
int PtraceBroker::RunImpl() {
while (true) {
Request request = {};
if (!ReadFileExactly(sock_, &request, sizeof(request))) {
return errno;
}
if (request.version != Request::kVersion) {
return EINVAL;
}
switch (request.type) {
case Request::kTypeAttach: {
ScopedPtraceAttach* attach;
ScopedPtraceAttach stack_attach;
bool attach_on_stack = false;
if (attach_capacity_ > attach_count_ || AllocateAttachments()) {
attach = new (&attachments_[attach_count_]) ScopedPtraceAttach;
} else {
attach = &stack_attach;
attach_on_stack = true;
}
Bool status = kBoolFalse;
if (attach->ResetAttach(request.tid)) {
status = kBoolTrue;
if (!attach_on_stack) {
++attach_count_;
}
}
if (!WriteFile(sock_, &status, sizeof(status))) {
return errno;
}
if (status == kBoolFalse) {
Errno error = errno;
if (!WriteFile(sock_, &error, sizeof(error))) {
return errno;
}
}
if (attach_on_stack && status == kBoolTrue) {
return RunImpl();
}
continue;
}
case Request::kTypeIs64Bit: {
Bool is_64_bit = ptracer_.Is64Bit() ? kBoolTrue : kBoolFalse;
if (!WriteFile(sock_, &is_64_bit, sizeof(is_64_bit))) {
return errno;
}
continue;
}
case Request::kTypeGetThreadInfo: {
GetThreadInfoResponse response;
response.success = ptracer_.GetThreadInfo(request.tid, &response.info)
? kBoolTrue
: kBoolFalse;
if (!WriteFile(sock_, &response, sizeof(response))) {
return errno;
}
if (response.success == kBoolFalse) {
Errno error = errno;
if (!WriteFile(sock_, &error, sizeof(error))) {
return errno;
}
}
continue;
}
case Request::kTypeReadMemory: {
int result =
SendMemory(request.tid, request.iov.base, request.iov.size);
if (result != 0) {
return result;
}
continue;
}
case Request::kTypeExit:
return 0;
}
DCHECK(false);
return EINVAL;
}
}
int PtraceBroker::SendMemory(pid_t pid, VMAddress address, VMSize size) {
char buffer[4096];
while (size > 0) {
VMSize bytes_read = std::min(size, VMSize{sizeof(buffer)});
if (!ptracer_.ReadMemory(pid, address, bytes_read, buffer)) {
bytes_read = 0;
Errno error = errno;
if (!WriteFile(sock_, &bytes_read, sizeof(bytes_read)) ||
!WriteFile(sock_, &error, sizeof(error))) {
return errno;
}
return 0;
}
if (!WriteFile(sock_, &bytes_read, sizeof(bytes_read))) {
return errno;
}
if (!WriteFile(sock_, buffer, bytes_read)) {
return errno;
}
size -= bytes_read;
address += bytes_read;
}
return 0;
}
bool PtraceBroker::AllocateAttachments() {
constexpr size_t page_size = 4096;
constexpr size_t alloc_size =
(sizeof(ScopedPtraceAttach) + page_size - 1) & ~(page_size - 1);
void* alloc = sbrk(alloc_size);
if (reinterpret_cast<intptr_t>(alloc) == -1) {
return false;
}
if (attachments_ == nullptr) {
attachments_ = reinterpret_cast<ScopedPtraceAttach*>(alloc);
}
attach_capacity_ += alloc_size / sizeof(ScopedPtraceAttach);
return true;
}
void PtraceBroker::ReleaseAttachments() {
for (size_t index = 0; index < attach_count_; ++index) {
attachments_[index].Reset();
}
}
} // namespace crashpad
// Copyright 2017 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_LINUX_PTRACE_BROKER_H_
#define CRASHPAD_UTIL_LINUX_PTRACE_BROKER_H_
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include "base/macros.h"
#include "util/linux/ptrace_connection.h"
#include "util/linux/ptracer.h"
#include "util/linux/scoped_ptrace_attach.h"
#include "util/linux/thread_info.h"
#include "util/misc/address_types.h"
namespace crashpad {
//! \brief Implements a PtraceConnection over a socket.
//!
//! This class is the server half of the connection. The broker should be run
//! in a process with `ptrace` capabilities for the target process and may run
//! in a compromised context.
class PtraceBroker {
public:
#pragma pack(push, 1)
//! \brief A request sent to a PtraceBroker from a PtraceClient.
struct Request {
static constexpr uint16_t kVersion = 1;
//! \brief The version number for this Request.
uint16_t version = kVersion;
//! \brief The type of request to serve.
enum Type : uint16_t {
//! \brief `ptrace`-attach the specified thread ID. Responds with
//! kBoolTrue on success, otherwise kBoolFalse, followed by an Errno.
kTypeAttach,
//! \brief Responds with kBoolTrue if the target process is 64-bit.
//! Otherwise, kBoolFalse.
kTypeIs64Bit,
//! \brief Responds with a GetThreadInfoResponse containing a ThreadInfo
//! for the specified thread ID. If an error occurs,
//! GetThreadInfoResponse::success is set to kBoolFalse and is
//! followed by an Errno.
kTypeGetThreadInfo,
//! \brief Reads memory from the attached process. The data is returned in
//! a series of messages. Each message begins with a VMSize indicating
//! the number of bytes being returned in this message, followed by
//! the requested bytes. The broker continues to send messages until
//! either all of the requested memory has been sent or an error
//! occurs, in which case it sends a message containing a VMSize equal
//! to zero, followed by an Errno.
kTypeReadMemory,
//! \brief Causes the broker to return from Run(), detaching all attached
//! threads. Does not respond.
kTypeExit
} type;
//! \brief The thread ID associated with this request. Valid for kTypeAttach,
//! kTypeGetThreadInfo, and kTypeReadMemory.
pid_t tid;
//! \brief Specifies the memory region to read for a kTypeReadMemory request.
struct {
//! \brief The base address of the memory region.
VMAddress base;
//! \brief The size of the memory region.
VMSize size;
} iov;
};
//! \brief The type used for error reporting.
using Errno = int32_t;
static_assert(sizeof(Errno) >= sizeof(errno), "Errno type is too small");
//! \brief A boolean status suitable for communication between processes.
enum Bool : char { kBoolFalse, kBoolTrue };
//! \brief The response sent for a Request with type kTypeGetThreadInfo.
struct GetThreadInfoResponse {
//! \brief Information about the specified thread. Only valid if #success
//! is kBoolTrue.
ThreadInfo info;
//! \brief Specifies the success or failure of this call.
Bool success;
};
#pragma pack(pop)
//! \brief Constructs this object.
//!
//! \param[in] sock A socket on which to read requests from a connected
//! PtraceClient. Does not take ownership of the socket.
//! \param[in] is_64_bit Whether this broker should be configured to trace a
//! 64-bit process.
PtraceBroker(int sock, bool is_64_bit);
~PtraceBroker();
//! \brief Begin serving requests on the configured socket.
//!
//! This method returns when a PtraceBrokerRequest with type kTypeExit is
//! received or an error is encountered on the socket.
//!
//! This method calls `sbrk`, which may break other memory management tools,
//! such as `malloc`.
//!
//! \return 0 if Run() exited due to an exit request. Otherwise an error code.
int Run();
private:
int RunImpl();
int SendMemory(pid_t pid, VMAddress address, VMSize size);
bool AllocateAttachments();
void ReleaseAttachments();
Ptracer ptracer_;
ScopedPtraceAttach* attachments_;
size_t attach_count_;
size_t attach_capacity_;
int sock_;
DISALLOW_COPY_AND_ASSIGN(PtraceBroker);
};
} // namespace crashpad
#endif // CRASHPAD_UTIL_LINUX_PTRACE_BROKER_H_
// Copyright 2017 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/linux/ptrace_broker.h"
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "util/file/file_io.h"
#include "util/linux/ptrace_client.h"
#include "util/posix/scoped_mmap.h"
#include "util/synchronization/semaphore.h"
#include "util/thread/thread.h"
namespace crashpad {
namespace test {
namespace {
class ScopedTimeoutThread : public Thread {
public:
ScopedTimeoutThread() : join_sem_(0) {}
~ScopedTimeoutThread() { EXPECT_TRUE(JoinWithTimeout(5.0)); }
protected:
void ThreadMain() override { join_sem_.Signal(); }
private:
bool JoinWithTimeout(double timeout) {
if (!join_sem_.TimedWait(timeout)) {
return false;
}
Join();
return true;
}
Semaphore join_sem_;
DISALLOW_COPY_AND_ASSIGN(ScopedTimeoutThread);
};
class RunBrokerThread : public ScopedTimeoutThread {
public:
RunBrokerThread(PtraceBroker* broker)
: ScopedTimeoutThread(), broker_(broker) {}
~RunBrokerThread() {}
private:
void ThreadMain() override {
EXPECT_EQ(broker_->Run(), 0);
ScopedTimeoutThread::ThreadMain();
}
PtraceBroker* broker_;
DISALLOW_COPY_AND_ASSIGN(RunBrokerThread);
};
class BlockOnReadThread : public ScopedTimeoutThread {
public:
BlockOnReadThread(int readfd, int writefd)
: ScopedTimeoutThread(), readfd_(readfd), writefd_(writefd) {}
~BlockOnReadThread() {}
private:
void ThreadMain() override {
pid_t pid = syscall(SYS_gettid);
LoggingWriteFile(writefd_, &pid, sizeof(pid));
LinuxVMAddress tls = GetTLS();
LoggingWriteFile(writefd_, &tls, sizeof(tls));
CheckedReadFileAtEOF(readfd_);
ScopedTimeoutThread::ThreadMain();
}
int readfd_;
int writefd_;
DISALLOW_COPY_AND_ASSIGN(BlockOnReadThread);
};
class SameBitnessTest : public Multiprocess {
public:
SameBitnessTest() : Multiprocess(), mapping_() {}
~SameBitnessTest() {}
protected:
void PreFork() override {
ASSERT_NO_FATAL_FAILURE(Multiprocess::PreFork());
size_t page_size = getpagesize();
ASSERT_TRUE(mapping_.ResetMmap(nullptr,
page_size * 3,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON,
-1,
0));
ASSERT_TRUE(mapping_.ResetAddrLen(mapping_.addr(), page_size * 2));
auto buffer = mapping_.addr_as<char*>();
for (size_t index = 0; index < mapping_.len(); ++index) {
buffer[index] = index % 256;
}
}
private:
void MultiprocessParent() override {
LinuxVMAddress child1_tls;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child1_tls, sizeof(child1_tls)));
pid_t child2_tid;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child2_tid, sizeof(child2_tid)));
LinuxVMAddress child2_tls;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child2_tls, sizeof(child2_tls)));
int socks[2];
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, socks), 0);
ScopedFileHandle broker_sock(socks[0]);
ScopedFileHandle client_sock(socks[1]);
#if defined(ARCH_CPU_64_BITS)
constexpr bool am_64_bit = true;
#else
constexpr bool am_64_bit = false;
#endif // ARCH_CPU_64_BITS
PtraceBroker broker(broker_sock.get(), am_64_bit);
RunBrokerThread broker_thread(&broker);
broker_thread.Start();
{
PtraceClient client;
ASSERT_TRUE(client.Initialize(client_sock.get(), ChildPID()));
EXPECT_EQ(client.GetProcessID(), ChildPID());
EXPECT_TRUE(client.Attach(child2_tid));
EXPECT_EQ(client.Is64Bit(), am_64_bit);
ThreadInfo info1;
ASSERT_TRUE(client.GetThreadInfo(ChildPID(), &info1));
EXPECT_EQ(info1.thread_specific_data_address, child1_tls);
ThreadInfo info2;
ASSERT_TRUE(client.GetThreadInfo(child2_tid, &info2));
EXPECT_EQ(info2.thread_specific_data_address, child2_tls);
auto buffer = std::make_unique<char[]>(mapping_.len());
ASSERT_TRUE(client.Read(
mapping_.addr_as<VMAddress>(), mapping_.len(), buffer.get()));
auto expected_buffer = mapping_.addr_as<char*>();
for (size_t index = 0; index < mapping_.len(); ++index) {
EXPECT_EQ(buffer[index], expected_buffer[index]);
}
char first;
ASSERT_TRUE(
client.Read(mapping_.addr_as<VMAddress>(), sizeof(first), &first));
EXPECT_EQ(first, expected_buffer[0]);
char last;
ASSERT_TRUE(
client.Read(mapping_.addr_as<VMAddress>() + mapping_.len() - 1,
sizeof(last),
&last));
EXPECT_EQ(last, expected_buffer[mapping_.len() - 1]);
char unmapped;
EXPECT_FALSE(client.Read(mapping_.addr_as<VMAddress>() + mapping_.len(),
sizeof(unmapped),
&unmapped));
}
}
void MultiprocessChild() override {
LinuxVMAddress tls = GetTLS();
ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), &tls, sizeof(tls)));
BlockOnReadThread thread(ReadPipeHandle(), WritePipeHandle());
thread.Start();
CheckedReadFileAtEOF(ReadPipeHandle());
}
ScopedMmap mapping_;
DISALLOW_COPY_AND_ASSIGN(SameBitnessTest);
};
TEST(PtraceBroker, SameBitness) {
SameBitnessTest test;
test.Run();
}
// TODO(jperaza): Test against a process with different bitness.
} // namespace
} // namespace test
} // namespace crashpad
// Copyright 2017 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/linux/ptrace_client.h"
#include <errno.h>
#include <string>
#include "base/logging.h"
#include "util/file/file_io.h"
#include "util/linux/ptrace_broker.h"
namespace crashpad {
namespace {
bool ReceiveAndLogError(int sock, const std::string& operation) {
PtraceBroker::Errno error;
if (!LoggingReadFileExactly(sock, &error, sizeof(error))) {
return false;
}
errno = error;
PLOG(ERROR) << operation;
return true;
}
bool AttachImpl(int sock, pid_t tid) {
PtraceBroker::Request request;
request.type = PtraceBroker::Request::kTypeAttach;
request.tid = tid;
if (!LoggingWriteFile(sock, &request, sizeof(request))) {
return false;
}
PtraceBroker::Bool success;
if (!LoggingReadFileExactly(sock, &success, sizeof(success))) {
return false;
}
if (success != PtraceBroker::kBoolTrue) {
ReceiveAndLogError(sock, "PtraceBroker Attach");
}
return true;
}
} // namespace
PtraceClient::PtraceClient()
: PtraceConnection(),
sock_(kInvalidFileHandle),
pid_(-1),
is_64_bit_(false),
initialized_() {}
PtraceClient::~PtraceClient() {
if (sock_ != kInvalidFileHandle) {
PtraceBroker::Request request;
request.type = PtraceBroker::Request::kTypeExit;
LoggingWriteFile(sock_, &request, sizeof(request));
}
}
bool PtraceClient::Initialize(int sock, pid_t pid) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
sock_ = sock;
pid_ = pid;
if (!AttachImpl(sock_, pid_)) {
return false;
}
PtraceBroker::Request request;
request.type = PtraceBroker::Request::kTypeIs64Bit;
request.tid = pid_;
if (!LoggingWriteFile(sock_, &request, sizeof(request))) {
return false;
}
PtraceBroker::Bool is_64_bit;
if (!LoggingReadFileExactly(sock_, &is_64_bit, sizeof(is_64_bit))) {
return false;
}
is_64_bit_ = is_64_bit == PtraceBroker::kBoolTrue;
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
pid_t PtraceClient::GetProcessID() {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return pid_;
}
bool PtraceClient::Attach(pid_t tid) {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return AttachImpl(sock_, tid);
}
bool PtraceClient::Is64Bit() {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return is_64_bit_;
}
bool PtraceClient::GetThreadInfo(pid_t tid, ThreadInfo* info) {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
PtraceBroker::Request request;
request.type = PtraceBroker::Request::kTypeGetThreadInfo;
request.tid = tid;
if (!LoggingWriteFile(sock_, &request, sizeof(request))) {
return false;
}
PtraceBroker::GetThreadInfoResponse response;
if (!LoggingReadFileExactly(sock_, &response, sizeof(response))) {
return false;
}
if (response.success == PtraceBroker::kBoolTrue) {
*info = response.info;
return true;
}
ReceiveAndLogError(sock_, "PtraceBroker GetThreadInfo");
return false;
}
bool PtraceClient::Read(VMAddress address, size_t size, void* buffer) {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
char* buffer_c = reinterpret_cast<char*>(buffer);
PtraceBroker::Request request;
request.type = PtraceBroker::Request::kTypeReadMemory;
request.tid = pid_;
request.iov.base = address;
request.iov.size = size;
if (!LoggingWriteFile(sock_, &request, sizeof(request))) {
return false;
}
while (size > 0) {
VMSize bytes_read;
if (!LoggingReadFileExactly(sock_, &bytes_read, sizeof(bytes_read))) {
return false;
}
if (!bytes_read) {
ReceiveAndLogError(sock_, "PtraceBroker ReadMemory");
return false;
}
if (!LoggingReadFileExactly(sock_, buffer_c, bytes_read)) {
return false;
}
size -= bytes_read;
buffer_c += bytes_read;
}
return true;
}
} // namespace crashpad
// Copyright 2017 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_LINUX_PTRACE_CLIENT_H_
#define CRASHPAD_UTIL_LINUX_PTRACE_CLIENT_H_
#include <sys/types.h>
#include "base/macros.h"
#include "util/linux/ptrace_connection.h"
#include "util/misc/address_types.h"
#include "util/misc/initialization_state_dcheck.h"
namespace crashpad {
//! \brief Implements a PtraceConnection over a socket.
//!
//! This class forms the client half of the connection and is typically used
//! when the current process does not have `ptrace` capabilities on the target
//! process. It should be created with a socket connected to a PtraceBroker.
class PtraceClient : public PtraceConnection {
public:
PtraceClient();
~PtraceClient();
//! \brief Initializes this object.
//!
//! This method must be successfully called before any other method in this
//! class.
//!
//! \param[in] sock A socket connected to a PtraceBroker. Does not take
//! ownership of the socket.
//! \param[in] pid The process ID of the process to form a PtraceConnection
//! with.
//! \return `true` on success. `false` on failure with a message logged.
bool Initialize(int sock, pid_t pid);
//! \brief Copies memory from the target process into a caller-provided buffer
//! in the current process.
//!
//! TODO(jperaza): In order for this to be usable, PtraceConnection will need
//! to surface it, possibly by inheriting from ProcessMemory, or providing a
//! method to return a ProcessMemory*.
//!
//! \param[in] address The address, in the target process' address space, of
//! the memory region to copy.
//! \param[in] size The size, in bytes, of the memory region to copy.
//! \a buffer must be at least this size.
//! \param[out] buffer The buffer into which the contents of the other
//! process' memory will be copied.
//!
//! \return `true` on success, with \a buffer filled appropriately. `false` on
//! failure, with a message logged.
bool Read(VMAddress address, size_t size, void* buffer);
// PtraceConnection:
pid_t GetProcessID() override;
bool Attach(pid_t tid) override;
bool Is64Bit() override;
bool GetThreadInfo(pid_t tid, ThreadInfo* info) override;
private:
int sock_;
pid_t pid_;
bool is_64_bit_;
InitializationStateDcheck initialized_;
DISALLOW_COPY_AND_ASSIGN(PtraceClient);
};
} // namespace crashpad
#endif // CRASHPAD_UTIL_LINUX_PTRACE_CLIENT_H_
......@@ -35,13 +35,16 @@ class Ptracer {
//! \brief Constructs this object with a pre-determined bitness.
//!
//! \param[in] is_64_bit `true` if this object is to be configured for 64-bit.
explicit Ptracer(bool is_64_bit);
//! \param[in] can_log Whether methods in this class can log error messages.
Ptracer(bool is_64_bit, bool can_log);
//! \brief Constructs this object without a pre-determined bitness.
//!
//! Initialize() must be successfully called before making any other calls on
//! this object.
Ptracer();
//!
//! \param[in] can_log Whether methods in this class can log error messages.
explicit Ptracer(bool can_log);
~Ptracer();
......@@ -49,7 +52,8 @@ class Ptracer {
//! ID is \a pid.
//!
//! \param[in] pid The process ID of the process to initialize with.
//! \return `true` on success. `false` on failure with a message logged.
//! \return `true` on success. `false` on failure with a message logged, if
//! enabled.
bool Initialize(pid_t pid);
//! \brief Return `true` if this object is configured for 64-bit.
......@@ -63,11 +67,27 @@ class Ptracer {
//!
//! \param[in] tid The thread ID of the thread to collect information for.
//! \param[out] info A ThreadInfo for the thread.
//! \return `true` on success. `false` on failure with a message logged.
//! \return `true` on success. `false` on failure with a message logged, if
//! enabled.
bool GetThreadInfo(pid_t tid, ThreadInfo* info);
//! \brief Uses `ptrace` to read memory from the process with process ID \a
//! pid.
//!
//! The target process should already be attached before calling this method.
//! \see ScopedPtraceAttach
//!
//! \param[in] pid The process ID whose memory to read.
//! \param[in] address The base address of the region to read.
//! \param[in] size The size of the memory region to read.
//! \param[out] buffer The buffer to fill with the data read.
//! \return `true` on success. `false` on failure with a message logged, if
//! enabled.
bool ReadMemory(pid_t pid, LinuxVMAddress address, size_t size, char* buffer);
private:
bool is_64_bit_;
bool can_log_;
InitializationStateDcheck initialized_;
DISALLOW_COPY_AND_ASSIGN(Ptracer);
......
......@@ -16,10 +16,10 @@
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "util/file/file_io.h"
#include "util/linux/scoped_ptrace_attach.h"
#include "util/misc/from_pointer_cast.h"
namespace crashpad {
namespace test {
......@@ -45,7 +45,7 @@ class SameBitnessTest : public Multiprocess {
ScopedPtraceAttach attach;
ASSERT_TRUE(attach.ResetAttach(ChildPID()));
Ptracer ptracer(am_64_bit);
Ptracer ptracer(am_64_bit, /* can_log= */ true);
EXPECT_EQ(ptracer.Is64Bit(), am_64_bit);
......@@ -60,24 +60,7 @@ class SameBitnessTest : public Multiprocess {
}
void MultiprocessChild() override {
LinuxVMAddress expected_tls;
#if defined(ARCH_CPU_ARMEL)
// 0xffff0fe0 is the address of the kernel user helper __kuser_get_tls().
auto kuser_get_tls = reinterpret_cast<void* (*)()>(0xffff0fe0);
expected_tls = FromPointerCast<LinuxVMAddress>(kuser_get_tls());
#elif defined(ARCH_CPU_ARM64)
// Linux/aarch64 places the tls address in system register tpidr_el0.
asm("mrs %0, tpidr_el0" : "=r"(expected_tls));
#elif defined(ARCH_CPU_X86)
uint32_t expected_tls_32;
asm("movl %%gs:0x0, %0" : "=r"(expected_tls_32));
expected_tls = expected_tls_32;
#elif defined(ARCH_CPU_X86_64)
asm("movq %%fs:0x0, %0" : "=r"(expected_tls));
#else
#error Port.
#endif // ARCH_CPU_ARMEL
LinuxVMAddress expected_tls = GetTLS();
CheckedWriteFile(WritePipeHandle(), &expected_tls, sizeof(expected_tls));
CheckedReadFileAtEOF(ReadPipeHandle());
......
......@@ -62,6 +62,10 @@
'linux/memory_map.h',
'linux/proc_stat_reader.cc',
'linux/proc_stat_reader.h',
'linux/ptrace_broker.cc',
'linux/ptrace_broker.h',
'linux/ptrace_client.cc',
'linux/ptrace_client.h'
'linux/ptrace_connection.h',
'linux/ptracer.cc',
'linux/ptracer.h',
......
......@@ -44,6 +44,7 @@
'linux/auxiliary_vector_test.cc',
'linux/memory_map_test.cc',
'linux/proc_stat_reader_test.cc',
'linux/ptrace_broker_test.cc',
'linux/ptracer_test.cc',
'linux/scoped_ptrace_attach_test.cc',
'mac/launchd_test.mm',
......@@ -169,18 +170,6 @@
'sources': [
'win/process_info_test_child.cc',
],
# Set an unusually high load address to make sure that the main
# executable still appears as the first element in
# ProcessInfo::Modules().
'msvs_settings': {
'VCLinkerTool': {
'AdditionalOptions': [
'/BASE:0x78000000',
],
'RandomizedBaseAddress': '1', # /DYNAMICBASE:NO.
'FixedBaseAddress': '2', # /FIXED.
},
},
},
{
'target_name': 'crashpad_util_test_safe_terminate_process_test_child',
......
......@@ -269,36 +269,15 @@ bool ReadProcessData(HANDLE process,
return false;
process_types::LDR_DATA_TABLE_ENTRY<Traits> ldr_data_table_entry;
// Include the first module in the memory order list to get our the main
// executable's name, as it's not included in initialization order below.
if (!ReadStruct(process,
static_cast<WinVMAddress>(
peb_ldr_data.InMemoryOrderModuleList.Flink) -
offsetof(process_types::LDR_DATA_TABLE_ENTRY<Traits>,
InMemoryOrderLinks),
&ldr_data_table_entry)) {
return false;
}
ProcessInfo::Module module;
if (!ReadUnicodeString(
process, ldr_data_table_entry.FullDllName, &module.name)) {
return false;
}
module.dll_base = ldr_data_table_entry.DllBase;
module.size = ldr_data_table_entry.SizeOfImage;
module.timestamp = ldr_data_table_entry.TimeDateStamp;
process_info->modules_.push_back(module);
// Walk the PEB LDR structure (doubly-linked list) to get the list of loaded
// modules. We use this method rather than EnumProcessModules to get the
// modules in initialization order rather than memory order.
typename Traits::Pointer last =
peb_ldr_data.InInitializationOrderModuleList.Blink;
for (typename Traits::Pointer cur =
peb_ldr_data.InInitializationOrderModuleList.Flink;
;
cur = ldr_data_table_entry.InInitializationOrderLinks.Flink) {
// modules in load order rather than memory order. Notably, this includes the
// main executable as the first element.
typename Traits::Pointer last = peb_ldr_data.InLoadOrderModuleList.Blink;
for (typename Traits::Pointer cur = peb_ldr_data.InLoadOrderModuleList.Flink;;
cur = ldr_data_table_entry.InLoadOrderLinks.Flink) {
// |cur| is the pointer to the LIST_ENTRY embedded in the
// LDR_DATA_TABLE_ENTRY, in the target process's address space. So we need
// to read from the target, and also offset back to the beginning of the
......@@ -306,14 +285,14 @@ bool ReadProcessData(HANDLE process,
if (!ReadStruct(process,
static_cast<WinVMAddress>(cur) -
offsetof(process_types::LDR_DATA_TABLE_ENTRY<Traits>,
InInitializationOrderLinks),
InLoadOrderLinks),
&ldr_data_table_entry)) {
break;
}
// TODO(scottmg): Capture Checksum, etc. too?
if (!ReadUnicodeString(
process, ldr_data_table_entry.FullDllName, &module.name)) {
break;
module.name = L"???";
}
module.dll_base = ldr_data_table_entry.DllBase;
module.size = ldr_data_table_entry.SizeOfImage;
......
......@@ -180,16 +180,22 @@ void TestOtherProcess(TestPaths::Architecture architecture) {
// lz32.dll is an uncommonly-used-but-always-available module that the test
// binary manually loads.
static constexpr wchar_t kLz32dllName[] = L"\\lz32.dll";
ASSERT_GE(modules.back().name.size(), wcslen(kLz32dllName));
EXPECT_EQ(modules.back().name.substr(modules.back().name.size() -
wcslen(kLz32dllName)),
auto& lz32 = modules[modules.size() - 2];
ASSERT_GE(lz32.name.size(), wcslen(kLz32dllName));
EXPECT_EQ(lz32.name.substr(lz32.name.size() - wcslen(kLz32dllName)),
kLz32dllName);
// Note that the test code corrupts the PEB MemoryOrder list, whereas
// ProcessInfo::Modules() retrieves the module names via the PEB LoadOrder
// list. These are expected to point to the same strings, but theoretically
// could be separate.
auto& corrupted = modules.back();
EXPECT_EQ(corrupted.name, L"???");
VerifyAddressInInCodePage(process_info, code_address);
}
// TODO(scottmg): https://crbug.com/792619.
TEST(ProcessInfo, DISABLED_OtherProcess) {
TEST(ProcessInfo, OtherProcess) {
TestOtherProcess(TestPaths::Architecture::kDefault);
}
......
......@@ -13,10 +13,26 @@
// limitations under the License.
#include <intrin.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
#include <winternl.h>
namespace {
bool UnicodeStringEndsWithCaseInsensitive(const UNICODE_STRING& us,
const wchar_t* ends_with) {
const size_t len = wcslen(ends_with);
// Recall that UNICODE_STRING.Length is in bytes, not characters.
const size_t us_len_in_chars = us.Length / sizeof(wchar_t);
if (us_len_in_chars < len)
return false;
return _wcsnicmp(&us.Buffer[us_len_in_chars - len], ends_with, len) == 0;
}
} // namespace
// A simple binary to be loaded and inspected by ProcessInfo.
int wmain(int argc, wchar_t** argv) {
......@@ -29,10 +45,49 @@ int wmain(int argc, wchar_t** argv) {
abort();
// Load an unusual module (that we don't depend upon) so we can do an
// existence check.
// existence check. It's also important that these DLLs don't depend on
// any other DLLs, otherwise there'll be additional modules in the list, which
// the test expects not to be there.
if (!LoadLibrary(L"lz32.dll"))
abort();
// Load another unusual module so we can destroy its FullDllName field in the
// PEB to test corrupted name reads.
static constexpr wchar_t kCorruptableDll[] = L"kbdurdu.dll";
if (!LoadLibrary(kCorruptableDll))
abort();
// Find and corrupt the buffer pointer to the name in the PEB.
HINSTANCE ntdll = GetModuleHandle(L"ntdll.dll");
decltype(NtQueryInformationProcess)* nt_query_information_process =
reinterpret_cast<decltype(NtQueryInformationProcess)*>(
GetProcAddress(ntdll, "NtQueryInformationProcess"));
if (!nt_query_information_process)
abort();
PROCESS_BASIC_INFORMATION pbi;
if (nt_query_information_process(GetCurrentProcess(),
ProcessBasicInformation,
&pbi,
sizeof(pbi),
nullptr) < 0) {
abort();
}
PEB_LDR_DATA* ldr = pbi.PebBaseAddress->Ldr;
LIST_ENTRY* head = &ldr->InMemoryOrderModuleList;
LIST_ENTRY* next = head->Flink;
while (next != head) {
LDR_DATA_TABLE_ENTRY* entry =
CONTAINING_RECORD(next, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
if (UnicodeStringEndsWithCaseInsensitive(entry->FullDllName,
kCorruptableDll)) {
// Corrupt the pointer to the name.
entry->FullDllName.Buffer = 0;
}
next = next->Flink;
}
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
if (out == INVALID_HANDLE_VALUE)
abort();
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment