Move all sources under atom/.

This commit is contained in:
Cheng Zhao 2014-03-16 08:30:26 +08:00
parent 26ddbbb0ee
commit 516d46444d
217 changed files with 519 additions and 519 deletions

View file

@ -0,0 +1,42 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/crash_reporter.h"
#include "base/command_line.h"
#include "atom/browser/browser.h"
#include "atom/common/atom_version.h"
#include "content/public/common/content_switches.h"
namespace crash_reporter {
CrashReporter::CrashReporter() {
const CommandLine& command = *CommandLine::ForCurrentProcess();
is_browser_ = command.GetSwitchValueASCII(switches::kProcessType).empty();
}
CrashReporter::~CrashReporter() {
}
void CrashReporter::Start(const std::string& product_name,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler,
const StringMap& extra_parameters) {
SetUploadParameters(extra_parameters);
InitBreakpad(product_name, ATOM_VERSION_STRING, company_name, submit_url,
auto_submit, skip_system_crash_handler);
}
void CrashReporter::SetUploadParameters(const StringMap& parameters) {
upload_parameters_ = parameters;
upload_parameters_["process_type"] = is_browser_ ? "browser" : "renderer";
// Setting platform dependent parameters.
SetUploadParameters();
}
} // namespace crash_reporter

View file

@ -0,0 +1,51 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_H_
#define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_H_
#include <map>
#include <string>
#include "base/basictypes.h"
namespace crash_reporter {
class CrashReporter {
public:
typedef std::map<std::string, std::string> StringMap;
static CrashReporter* GetInstance();
void Start(const std::string& product_name,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler,
const StringMap& extra_parameters);
protected:
CrashReporter();
virtual ~CrashReporter();
virtual void InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) = 0;
virtual void SetUploadParameters() = 0;
StringMap upload_parameters_;
bool is_browser_;
private:
void SetUploadParameters(const StringMap& parameters);
DISALLOW_COPY_AND_ASSIGN(CrashReporter);
};
} // namespace crash_reporter
#endif // ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_H_

View file

@ -0,0 +1,134 @@
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/crash_reporter_linux.h"
#include <sys/time.h>
#include <unistd.h>
#include "base/debug/crash_logging.h"
#include "base/files/file_path.h"
#include "base/linux_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process/memory.h"
#include "base/memory/singleton.h"
#include "vendor/breakpad/src/client/linux/handler/exception_handler.h"
#include "vendor/breakpad/src/common/linux/linux_libc_support.h"
using google_breakpad::ExceptionHandler;
using google_breakpad::MinidumpDescriptor;
namespace crash_reporter {
namespace {
static const size_t kDistroSize = 128;
// Define a preferred limit on minidump sizes, because Crash Server currently
// throws away any larger than 1.2MB (1.2 * 1024 * 1024). A value of -1 means
// no limit.
static const off_t kMaxMinidumpFileSize = 1258291;
} // namespace
CrashReporterLinux::CrashReporterLinux()
: process_start_time_(0),
pid_(getpid()) {
// Set the base process start time value.
struct timeval tv;
if (!gettimeofday(&tv, NULL)) {
uint64_t ret = tv.tv_sec;
ret *= 1000;
ret += tv.tv_usec / 1000;
process_start_time_ = ret;
}
// Make base::g_linux_distro work.
base::SetLinuxDistro(base::GetLinuxDistro());
}
CrashReporterLinux::~CrashReporterLinux() {
}
void CrashReporterLinux::InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) {
EnableCrashDumping();
crash_keys_.SetKeyValue("prod", "Atom-Shell");
crash_keys_.SetKeyValue("ver", version.c_str());
upload_url_ = submit_url;
for (StringMap::const_iterator iter = upload_parameters_.begin();
iter != upload_parameters_.end(); ++iter)
crash_keys_.SetKeyValue(iter->first.c_str(), iter->second.c_str());
}
void CrashReporterLinux::SetUploadParameters() {
upload_parameters_["platform"] = "linux";
}
void CrashReporterLinux::EnableCrashDumping() {
base::FilePath tmp_path("/tmp");
PathService::Get(base::DIR_TEMP, &tmp_path);
base::FilePath dumps_path(tmp_path);
MinidumpDescriptor minidump_descriptor(dumps_path.value());
minidump_descriptor.set_size_limit(kMaxMinidumpFileSize);
breakpad_.reset(new ExceptionHandler(
minidump_descriptor,
NULL,
CrashDone,
this,
true, // Install handlers.
-1));
}
bool CrashReporterLinux::CrashDone(const MinidumpDescriptor& minidump,
void* context,
const bool succeeded) {
CrashReporterLinux* self = static_cast<CrashReporterLinux*>(context);
// WARNING: this code runs in a compromised context. It may not call into
// libc nor allocate memory normally.
if (!succeeded) {
const char msg[] = "Failed to generate minidump.";
WriteLog(msg, sizeof(msg) - 1);
return false;
}
DCHECK(!minidump.IsFD());
BreakpadInfo info = {0};
info.filename = minidump.path();
info.fd = minidump.fd();
info.distro = base::g_linux_distro;
info.distro_length = my_strlen(base::g_linux_distro);
info.upload = true;
info.process_start_time = self->process_start_time_;
info.oom_size = base::g_oom_size;
info.pid = self->pid_;
info.upload_url = self->upload_url_.c_str();
info.crash_keys = &self->crash_keys_;
HandleCrashDump(info);
return true;
}
// static
CrashReporterLinux* CrashReporterLinux::GetInstance() {
return Singleton<CrashReporterLinux>::get();
}
// static
CrashReporter* CrashReporter::GetInstance() {
return CrashReporterLinux::GetInstance();
}
} // namespace crash_reporter

View file

@ -0,0 +1,57 @@
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_LINUX_H_
#define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_LINUX_H_
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "atom/common/crash_reporter/crash_reporter.h"
#include "atom/common/crash_reporter/linux/crash_dump_handler.h"
template <typename T> struct DefaultSingletonTraits;
namespace google_breakpad {
class ExceptionHandler;
class MinidumpDescriptor;
}
namespace crash_reporter {
class CrashReporterLinux : public CrashReporter {
public:
static CrashReporterLinux* GetInstance();
virtual void InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) OVERRIDE;
virtual void SetUploadParameters() OVERRIDE;
private:
friend struct DefaultSingletonTraits<CrashReporterLinux>;
CrashReporterLinux();
virtual ~CrashReporterLinux();
void EnableCrashDumping();
static bool CrashDone(const google_breakpad::MinidumpDescriptor& minidump,
void* context,
const bool succeeded);
scoped_ptr<google_breakpad::ExceptionHandler> breakpad_;
CrashKeyStorage crash_keys_;
uint64_t process_start_time_;
pid_t pid_;
std::string upload_url_;
DISALLOW_COPY_AND_ASSIGN(CrashReporterLinux);
};
} // namespace crash_reporter
#endif // ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_LINUX_H_

View file

@ -0,0 +1,41 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_
#define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_
#include "base/compiler_specific.h"
#include "atom/common/crash_reporter/crash_reporter.h"
#import "vendor/breakpad/src/client/mac/Framework/Breakpad.h"
template <typename T> struct DefaultSingletonTraits;
namespace crash_reporter {
class CrashReporterMac : public CrashReporter {
public:
static CrashReporterMac* GetInstance();
virtual void InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) OVERRIDE;
virtual void SetUploadParameters() OVERRIDE;
private:
friend struct DefaultSingletonTraits<CrashReporterMac>;
CrashReporterMac();
virtual ~CrashReporterMac();
BreakpadRef breakpad_;
DISALLOW_COPY_AND_ASSIGN(CrashReporterMac);
};
} // namespace crash_reporter
#endif // ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_

View file

@ -0,0 +1,81 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/crash_reporter_mac.h"
#include "base/memory/singleton.h"
#include "base/strings/sys_string_conversions.h"
#import "vendor/breakpad/src/client/apple/Framework/BreakpadDefines.h"
namespace crash_reporter {
CrashReporterMac::CrashReporterMac()
: breakpad_(NULL) {
}
CrashReporterMac::~CrashReporterMac() {
if (breakpad_ != NULL)
BreakpadRelease(breakpad_);
}
void CrashReporterMac::InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) {
if (breakpad_ != NULL)
BreakpadRelease(breakpad_);
NSMutableDictionary* parameters =
[NSMutableDictionary dictionaryWithCapacity:4];
[parameters setValue:@"Atom-Shell"
forKey:@BREAKPAD_PRODUCT];
[parameters setValue:base::SysUTF8ToNSString(product_name)
forKey:@BREAKPAD_PRODUCT_DISPLAY];
[parameters setValue:base::SysUTF8ToNSString(version)
forKey:@BREAKPAD_VERSION];
[parameters setValue:base::SysUTF8ToNSString(company_name)
forKey:@BREAKPAD_VENDOR];
[parameters setValue:base::SysUTF8ToNSString(submit_url)
forKey:@BREAKPAD_URL];
[parameters setValue:(auto_submit ? @"YES" : @"NO")
forKey:@BREAKPAD_SKIP_CONFIRM];
[parameters setValue:(skip_system_crash_handler ? @"YES" : @"NO")
forKey:@BREAKPAD_SEND_AND_EXIT];
// Report all crashes (important for testing the crash reporter).
[parameters setValue:@"0" forKey:@BREAKPAD_REPORT_INTERVAL];
// Put dump files under "/tmp/ProductName Crashes".
std::string dump_dir = "/tmp/" + product_name + " Crashes";
[parameters setValue:base::SysUTF8ToNSString(dump_dir)
forKey:@BREAKPAD_DUMP_DIRECTORY];
breakpad_ = BreakpadCreate(parameters);
for (StringMap::const_iterator iter = upload_parameters_.begin();
iter != upload_parameters_.end(); ++iter) {
BreakpadAddUploadParameter(breakpad_,
base::SysUTF8ToNSString(iter->first),
base::SysUTF8ToNSString(iter->second));
}
}
void CrashReporterMac::SetUploadParameters() {
upload_parameters_["platform"] = "darwin";
}
// static
CrashReporterMac* CrashReporterMac::GetInstance() {
return Singleton<CrashReporterMac>::get();
}
// static
CrashReporter* CrashReporter::GetInstance() {
return CrashReporterMac::GetInstance();
}
} // namespace crash_reporter

View file

@ -0,0 +1,129 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/crash_reporter_win.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
namespace crash_reporter {
namespace {
// Minidump with stacks, PEB, TEB, and unloaded module list.
const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
MiniDumpWithProcessThreadData | // Get PEB and TEB.
MiniDumpWithUnloadedModules); // Get unloaded modules when available.
const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service";
} // namespace
CrashReporterWin::CrashReporterWin() {
}
CrashReporterWin::~CrashReporterWin() {
}
void CrashReporterWin::InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) {
skip_system_crash_handler_ = skip_system_crash_handler;
base::FilePath temp_dir;
if (!file_util::GetTempDir(&temp_dir)) {
LOG(ERROR) << "Cannot get temp directory";
return;
}
string16 pipe_name = ReplaceStringPlaceholders(kPipeNameFormat,
UTF8ToUTF16(product_name),
NULL);
// Wait until the crash service is started.
HANDLE waiting_event =
::CreateEventW(NULL, TRUE, FALSE, L"g_atom_shell_crash_service");
if (waiting_event != INVALID_HANDLE_VALUE)
WaitForSingleObject(waiting_event, 1000);
breakpad_.reset(new google_breakpad::ExceptionHandler(
temp_dir.value(),
FilterCallback,
MinidumpCallback,
this,
google_breakpad::ExceptionHandler::HANDLER_ALL,
kSmallDumpType,
pipe_name.c_str(),
GetCustomInfo(product_name, version, company_name)));
if (!breakpad_->IsOutOfProcess())
LOG(ERROR) << "Cannot initialize out-of-process crash handler";
}
void CrashReporterWin::SetUploadParameters() {
upload_parameters_["platform"] = "win32";
}
// static
bool CrashReporterWin::FilterCallback(void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion) {
return true;
}
// static
bool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,
const wchar_t* minidump_id,
void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion,
bool succeeded) {
CrashReporterWin* self = static_cast<CrashReporterWin*>(context);
if (succeeded && !self->skip_system_crash_handler_)
return true;
else
return false;
}
google_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(
const std::string& product_name,
const std::string& version,
const std::string& company_name) {
custom_info_entries_.clear();
custom_info_entries_.reserve(2 + upload_parameters_.size());
custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
L"prod", L"Atom-Shell"));
custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
L"ver", UTF8ToWide(version).c_str()));
for (StringMap::const_iterator iter = upload_parameters_.begin();
iter != upload_parameters_.end(); ++iter) {
custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
UTF8ToWide(iter->first).c_str(),
UTF8ToWide(iter->second).c_str()));
}
custom_info_.entries = &custom_info_entries_.front();
custom_info_.count = custom_info_entries_.size();
return &custom_info_;
}
// static
CrashReporterWin* CrashReporterWin::GetInstance() {
return Singleton<CrashReporterWin>::get();
}
// static
CrashReporter* CrashReporter::GetInstance() {
return CrashReporterWin::GetInstance();
}
} // namespace crash_reporter

View file

@ -0,0 +1,64 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_WIN_H_
#define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_WIN_H_
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "atom/common/crash_reporter/crash_reporter.h"
#include "vendor/breakpad/src/client/windows/handler/exception_handler.h"
template <typename T> struct DefaultSingletonTraits;
namespace crash_reporter {
class CrashReporterWin : public CrashReporter {
public:
static CrashReporterWin* GetInstance();
virtual void InitBreakpad(const std::string& product_name,
const std::string& version,
const std::string& company_name,
const std::string& submit_url,
bool auto_submit,
bool skip_system_crash_handler) OVERRIDE;
virtual void SetUploadParameters() OVERRIDE;
private:
friend struct DefaultSingletonTraits<CrashReporterWin>;
CrashReporterWin();
virtual ~CrashReporterWin();
static bool FilterCallback(void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion);
static bool MinidumpCallback(const wchar_t* dump_path,
const wchar_t* minidump_id,
void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion,
bool succeeded);
// Returns the custom info structure based on parameters.
google_breakpad::CustomClientInfo* GetCustomInfo(
const std::string& product_name,
const std::string& version,
const std::string& company_name);
// Custom information to be passed to crash handler.
std::vector<google_breakpad::CustomInfoEntry> custom_info_entries_;
google_breakpad::CustomClientInfo custom_info_;
bool skip_system_crash_handler_;
scoped_ptr<google_breakpad::ExceptionHandler> breakpad_;
DISALLOW_COPY_AND_ASSIGN(CrashReporterWin);
};
} // namespace crash_reporter
#endif // ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_WIN_H_

View file

@ -0,0 +1,668 @@
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For linux_syscall_support.h. This makes it safe to call embedded system
// calls when in seccomp mode.
#include "atom/common/crash_reporter/linux/crash_dump_handler.h"
#include <poll.h>
#include <algorithm>
#include "base/posix/eintr_wrapper.h"
#include "vendor/breakpad/src/client/linux/minidump_writer/directory_reader.h"
#include "vendor/breakpad/src/common/linux/linux_libc_support.h"
#include "vendor/breakpad/src/common/memory.h"
#include "third_party/lss/linux_syscall_support.h"
// Some versions of gcc are prone to warn about unused return values. In cases
// where we either a) know the call cannot fail, or b) there is nothing we
// can do when a call fails, we mark the return code as ignored. This avoids
// spurious compiler warnings.
#define IGNORE_RET(x) do { if (x); } while (0)
namespace crash_reporter {
namespace {
// String buffer size to use to convert a uint64_t to string.
const size_t kUint64StringSize = 21;
// Writes the value |v| as 16 hex characters to the memory pointed at by
// |output|.
void write_uint64_hex(char* output, uint64_t v) {
static const char hextable[] = "0123456789abcdef";
for (int i = 15; i >= 0; --i) {
output[i] = hextable[v & 15];
v >>= 4;
}
}
// uint64_t version of my_int_len() from
// breakpad/src/common/linux/linux_libc_support.h. Return the length of the
// given, non-negative integer when expressed in base 10.
unsigned my_uint64_len(uint64_t i) {
if (!i)
return 1;
unsigned len = 0;
while (i) {
len++;
i /= 10;
}
return len;
}
// uint64_t version of my_uitos() from
// breakpad/src/common/linux/linux_libc_support.h. Convert a non-negative
// integer to a string (not null-terminated).
void my_uint64tos(char* output, uint64_t i, unsigned i_len) {
for (unsigned index = i_len; index; --index, i /= 10)
output[index - 1] = '0' + (i % 10);
}
// Converts a struct timeval to milliseconds.
uint64_t kernel_timeval_to_ms(struct kernel_timeval *tv) {
uint64_t ret = tv->tv_sec; // Avoid overflow by explicitly using a uint64_t.
ret *= 1000;
ret += tv->tv_usec / 1000;
return ret;
}
size_t LengthWithoutTrailingSpaces(const char* str, size_t len) {
while (len > 0 && str[len - 1] == ' ') {
len--;
}
return len;
}
// MIME substrings.
const char g_rn[] = "\r\n";
const char g_form_data_msg[] = "Content-Disposition: form-data; name=\"";
const char g_quote_msg[] = "\"";
const char g_dashdash_msg[] = "--";
const char g_dump_msg[] = "upload_file_minidump\"; filename=\"dump\"";
const char g_content_type_msg[] = "Content-Type: application/octet-stream";
// MimeWriter manages an iovec for writing MIMEs to a file.
class MimeWriter {
public:
static const int kIovCapacity = 30;
static const size_t kMaxCrashChunkSize = 64;
MimeWriter(int fd, const char* const mime_boundary);
~MimeWriter();
// Append boundary.
virtual void AddBoundary();
// Append end of file boundary.
virtual void AddEnd();
// Append key/value pair with specified sizes.
virtual void AddPairData(const char* msg_type,
size_t msg_type_size,
const char* msg_data,
size_t msg_data_size);
// Append key/value pair.
void AddPairString(const char* msg_type,
const char* msg_data) {
AddPairData(msg_type, my_strlen(msg_type), msg_data, my_strlen(msg_data));
}
// Append key/value pair, splitting value into chunks no larger than
// |chunk_size|. |chunk_size| cannot be greater than |kMaxCrashChunkSize|.
// The msg_type string will have a counter suffix to distinguish each chunk.
virtual void AddPairDataInChunks(const char* msg_type,
size_t msg_type_size,
const char* msg_data,
size_t msg_data_size,
size_t chunk_size,
bool strip_trailing_spaces);
// Add binary file contents to be uploaded with the specified filename.
virtual void AddFileContents(const char* filename_msg,
uint8_t* file_data,
size_t file_size);
// Flush any pending iovecs to the output file.
void Flush() {
IGNORE_RET(sys_writev(fd_, iov_, iov_index_));
iov_index_ = 0;
}
protected:
void AddItem(const void* base, size_t size);
// Minor performance trade-off for easier-to-maintain code.
void AddString(const char* str) {
AddItem(str, my_strlen(str));
}
void AddItemWithoutTrailingSpaces(const void* base, size_t size);
struct kernel_iovec iov_[kIovCapacity];
int iov_index_;
// Output file descriptor.
int fd_;
const char* const mime_boundary_;
private:
DISALLOW_COPY_AND_ASSIGN(MimeWriter);
};
MimeWriter::MimeWriter(int fd, const char* const mime_boundary)
: iov_index_(0),
fd_(fd),
mime_boundary_(mime_boundary) {
}
MimeWriter::~MimeWriter() {
}
void MimeWriter::AddBoundary() {
AddString(mime_boundary_);
AddString(g_rn);
}
void MimeWriter::AddEnd() {
AddString(mime_boundary_);
AddString(g_dashdash_msg);
AddString(g_rn);
}
void MimeWriter::AddPairData(const char* msg_type,
size_t msg_type_size,
const char* msg_data,
size_t msg_data_size) {
AddString(g_form_data_msg);
AddItem(msg_type, msg_type_size);
AddString(g_quote_msg);
AddString(g_rn);
AddString(g_rn);
AddItem(msg_data, msg_data_size);
AddString(g_rn);
}
void MimeWriter::AddPairDataInChunks(const char* msg_type,
size_t msg_type_size,
const char* msg_data,
size_t msg_data_size,
size_t chunk_size,
bool strip_trailing_spaces) {
if (chunk_size > kMaxCrashChunkSize)
return;
unsigned i = 0;
size_t done = 0, msg_length = msg_data_size;
while (msg_length) {
char num[kUint64StringSize];
const unsigned num_len = my_uint_len(++i);
my_uitos(num, i, num_len);
size_t chunk_len = std::min(chunk_size, msg_length);
AddString(g_form_data_msg);
AddItem(msg_type, msg_type_size);
AddItem(num, num_len);
AddString(g_quote_msg);
AddString(g_rn);
AddString(g_rn);
if (strip_trailing_spaces) {
AddItemWithoutTrailingSpaces(msg_data + done, chunk_len);
} else {
AddItem(msg_data + done, chunk_len);
}
AddString(g_rn);
AddBoundary();
Flush();
done += chunk_len;
msg_length -= chunk_len;
}
}
void MimeWriter::AddFileContents(const char* filename_msg, uint8_t* file_data,
size_t file_size) {
AddString(g_form_data_msg);
AddString(filename_msg);
AddString(g_rn);
AddString(g_content_type_msg);
AddString(g_rn);
AddString(g_rn);
AddItem(file_data, file_size);
AddString(g_rn);
}
void MimeWriter::AddItem(const void* base, size_t size) {
// Check if the iovec is full and needs to be flushed to output file.
if (iov_index_ == kIovCapacity) {
Flush();
}
iov_[iov_index_].iov_base = const_cast<void*>(base);
iov_[iov_index_].iov_len = size;
++iov_index_;
}
void MimeWriter::AddItemWithoutTrailingSpaces(const void* base, size_t size) {
AddItem(base, LengthWithoutTrailingSpaces(static_cast<const char*>(base),
size));
}
void LoadDataFromFD(google_breakpad::PageAllocator* allocator,
int fd, bool close_fd, uint8_t** file_data, size_t* size) {
struct kernel_stat st;
if (sys_fstat(fd, &st) != 0) {
static const char msg[] = "Cannot upload crash dump: stat failed\n";
WriteLog(msg, sizeof(msg) - 1);
if (close_fd)
IGNORE_RET(sys_close(fd));
return;
}
*file_data = reinterpret_cast<uint8_t*>(allocator->Alloc(st.st_size));
if (!(*file_data)) {
static const char msg[] = "Cannot upload crash dump: cannot alloc\n";
WriteLog(msg, sizeof(msg) - 1);
if (close_fd)
IGNORE_RET(sys_close(fd));
return;
}
my_memset(*file_data, 0xf, st.st_size);
*size = st.st_size;
int byte_read = sys_read(fd, *file_data, *size);
if (byte_read == -1) {
static const char msg[] = "Cannot upload crash dump: read failed\n";
WriteLog(msg, sizeof(msg) - 1);
if (close_fd)
IGNORE_RET(sys_close(fd));
return;
}
if (close_fd)
IGNORE_RET(sys_close(fd));
}
void LoadDataFromFile(google_breakpad::PageAllocator* allocator,
const char* filename,
int* fd, uint8_t** file_data, size_t* size) {
// WARNING: this code runs in a compromised context. It may not call into
// libc nor allocate memory normally.
*fd = sys_open(filename, O_RDONLY, 0);
*size = 0;
if (*fd < 0) {
static const char msg[] = "Cannot upload crash dump: failed to open\n";
WriteLog(msg, sizeof(msg) - 1);
return;
}
LoadDataFromFD(allocator, *fd, true, file_data, size);
}
// Spawn the appropriate upload process for the current OS:
// - generic Linux invokes wget.
// - ChromeOS invokes crash_reporter.
// |dumpfile| is the path to the dump data file.
// |mime_boundary| is only used on Linux.
// |exe_buf| is only used on CrOS and is the crashing process' name.
void ExecUploadProcessOrTerminate(const BreakpadInfo& info,
const char* dumpfile,
const char* mime_boundary,
const char* exe_buf,
google_breakpad::PageAllocator* allocator) {
// The --header argument to wget looks like:
// --header=Content-Type: multipart/form-data; boundary=XYZ
// where the boundary has two fewer leading '-' chars
static const char header_msg[] =
"--header=Content-Type: multipart/form-data; boundary=";
char* const header = reinterpret_cast<char*>(allocator->Alloc(
sizeof(header_msg) - 1 + strlen(mime_boundary) - 2 + 1));
memcpy(header, header_msg, sizeof(header_msg) - 1);
memcpy(header + sizeof(header_msg) - 1, mime_boundary + 2,
strlen(mime_boundary) - 2);
// We grab the NUL byte from the end of |mime_boundary|.
// The --post-file argument to wget looks like:
// --post-file=/tmp/...
static const char post_file_msg[] = "--post-file=";
char* const post_file = reinterpret_cast<char*>(allocator->Alloc(
sizeof(post_file_msg) - 1 + strlen(dumpfile) + 1));
memcpy(post_file, post_file_msg, sizeof(post_file_msg) - 1);
memcpy(post_file + sizeof(post_file_msg) - 1, dumpfile, strlen(dumpfile));
static const char kWgetBinary[] = "/usr/bin/wget";
const char* args[] = {
kWgetBinary,
header,
post_file,
// TODO(zcbenz): Enabling custom upload url.
info.upload_url,
"--timeout=10", // Set a timeout so we don't hang forever.
"--tries=1", // Don't retry if the upload fails.
"-O", // output reply to fd 3
"/dev/fd/3",
NULL,
};
static const char msg[] = "Cannot upload crash dump: cannot exec "
"/usr/bin/wget\n";
execve(args[0], const_cast<char**>(args), environ);
WriteLog(msg, sizeof(msg) - 1);
sys__exit(1);
}
} // namespace
void HandleCrashDump(const BreakpadInfo& info) {
int dumpfd;
bool keep_fd = false;
size_t dump_size;
uint8_t* dump_data;
google_breakpad::PageAllocator allocator;
const char* exe_buf = NULL;
if (info.fd != -1) {
// Dump is provided with an open FD.
keep_fd = true;
dumpfd = info.fd;
// The FD is pointing to the end of the file.
// Rewind, we'll read the data next.
if (lseek(dumpfd, 0, SEEK_SET) == -1) {
static const char msg[] = "Cannot upload crash dump: failed to "
"reposition minidump FD\n";
WriteLog(msg, sizeof(msg) - 1);
IGNORE_RET(sys_close(dumpfd));
return;
}
LoadDataFromFD(&allocator, info.fd, false, &dump_data, &dump_size);
} else {
// Dump is provided with a path.
keep_fd = false;
LoadDataFromFile(
&allocator, info.filename, &dumpfd, &dump_data, &dump_size);
}
// We need to build a MIME block for uploading to the server. Since we are
// going to fork and run wget, it needs to be written to a temp file.
const int ufd = sys_open("/dev/urandom", O_RDONLY, 0);
if (ufd < 0) {
static const char msg[] = "Cannot upload crash dump because /dev/urandom"
" is missing\n";
WriteLog(msg, sizeof(msg) - 1);
return;
}
static const char temp_file_template[] =
"/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
char temp_file[sizeof(temp_file_template)];
int temp_file_fd = -1;
if (keep_fd) {
temp_file_fd = dumpfd;
// Rewind the destination, we are going to overwrite it.
if (lseek(dumpfd, 0, SEEK_SET) == -1) {
static const char msg[] = "Cannot upload crash dump: failed to "
"reposition minidump FD (2)\n";
WriteLog(msg, sizeof(msg) - 1);
IGNORE_RET(sys_close(dumpfd));
return;
}
} else {
if (info.upload) {
memcpy(temp_file, temp_file_template, sizeof(temp_file_template));
for (unsigned i = 0; i < 10; ++i) {
uint64_t t;
sys_read(ufd, &t, sizeof(t));
write_uint64_hex(temp_file + sizeof(temp_file) - (16 + 1), t);
temp_file_fd = sys_open(temp_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (temp_file_fd >= 0)
break;
}
if (temp_file_fd < 0) {
static const char msg[] = "Failed to create temporary file in /tmp: "
"cannot upload crash dump\n";
WriteLog(msg, sizeof(msg) - 1);
IGNORE_RET(sys_close(ufd));
return;
}
} else {
temp_file_fd = sys_open(info.filename, O_WRONLY, 0600);
if (temp_file_fd < 0) {
static const char msg[] = "Failed to save crash dump: failed to open\n";
WriteLog(msg, sizeof(msg) - 1);
IGNORE_RET(sys_close(ufd));
return;
}
}
}
// The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
char mime_boundary[28 + 16 + 1];
my_memset(mime_boundary, '-', 28);
uint64_t boundary_rand;
sys_read(ufd, &boundary_rand, sizeof(boundary_rand));
write_uint64_hex(mime_boundary + 28, boundary_rand);
mime_boundary[28 + 16] = 0;
IGNORE_RET(sys_close(ufd));
// The MIME block looks like this:
// BOUNDARY \r\n
// Content-Disposition: form-data; name="prod" \r\n \r\n
// Chrome_Linux \r\n
// BOUNDARY \r\n
// Content-Disposition: form-data; name="ver" \r\n \r\n
// 1.2.3.4 \r\n
// BOUNDARY \r\n
//
// zero or one:
// Content-Disposition: form-data; name="ptime" \r\n \r\n
// abcdef \r\n
// BOUNDARY \r\n
//
// zero or one:
// Content-Disposition: form-data; name="ptype" \r\n \r\n
// abcdef \r\n
// BOUNDARY \r\n
//
// zero or one:
// Content-Disposition: form-data; name="lsb-release" \r\n \r\n
// abcdef \r\n
// BOUNDARY \r\n
//
// zero or one:
// Content-Disposition: form-data; name="oom-size" \r\n \r\n
// 1234567890 \r\n
// BOUNDARY \r\n
//
// zero or more (up to CrashKeyStorage::num_entries = 64):
// Content-Disposition: form-data; name=crash-key-name \r\n
// crash-key-value \r\n
// BOUNDARY \r\n
//
// Content-Disposition: form-data; name="dump"; filename="dump" \r\n
// Content-Type: application/octet-stream \r\n \r\n
// <dump contents>
// \r\n BOUNDARY -- \r\n
MimeWriter writer(temp_file_fd, mime_boundary);
{
writer.AddBoundary();
if (info.pid > 0) {
char pid_value_buf[kUint64StringSize];
uint64_t pid_value_len = my_uint64_len(info.pid);
my_uint64tos(pid_value_buf, info.pid, pid_value_len);
static const char pid_key_name[] = "pid";
writer.AddPairData(pid_key_name, sizeof(pid_key_name) - 1,
pid_value_buf, pid_value_len);
writer.AddBoundary();
}
writer.Flush();
}
if (info.process_start_time > 0) {
struct kernel_timeval tv;
if (!sys_gettimeofday(&tv, NULL)) {
uint64_t time = kernel_timeval_to_ms(&tv);
if (time > info.process_start_time) {
time -= info.process_start_time;
char time_str[kUint64StringSize];
const unsigned time_len = my_uint64_len(time);
my_uint64tos(time_str, time, time_len);
static const char process_time_msg[] = "ptime";
writer.AddPairData(process_time_msg, sizeof(process_time_msg) - 1,
time_str, time_len);
writer.AddBoundary();
writer.Flush();
}
}
}
if (info.distro_length) {
static const char distro_msg[] = "lsb-release";
writer.AddPairString(distro_msg, info.distro);
writer.AddBoundary();
writer.Flush();
}
if (info.oom_size) {
char oom_size_str[kUint64StringSize];
const unsigned oom_size_len = my_uint64_len(info.oom_size);
my_uint64tos(oom_size_str, info.oom_size, oom_size_len);
static const char oom_size_msg[] = "oom-size";
writer.AddPairData(oom_size_msg, sizeof(oom_size_msg) - 1,
oom_size_str, oom_size_len);
writer.AddBoundary();
writer.Flush();
}
if (info.crash_keys) {
CrashKeyStorage::Iterator crash_key_iterator(*info.crash_keys);
const CrashKeyStorage::Entry* entry;
while ((entry = crash_key_iterator.Next())) {
writer.AddPairString(entry->key, entry->value);
writer.AddBoundary();
writer.Flush();
}
}
writer.AddFileContents(g_dump_msg, dump_data, dump_size);
writer.AddEnd();
writer.Flush();
IGNORE_RET(sys_close(temp_file_fd));
if (!info.upload)
return;
const pid_t child = sys_fork();
if (!child) {
// Spawned helper process.
//
// This code is called both when a browser is crashing (in which case,
// nothing really matters any more) and when a renderer/plugin crashes, in
// which case we need to continue.
//
// Since we are a multithreaded app, if we were just to fork(), we might
// grab file descriptors which have just been created in another thread and
// hold them open for too long.
//
// Thus, we have to loop and try and close everything.
const int fd = sys_open("/proc/self/fd", O_DIRECTORY | O_RDONLY, 0);
if (fd < 0) {
for (unsigned i = 3; i < 8192; ++i)
IGNORE_RET(sys_close(i));
} else {
google_breakpad::DirectoryReader reader(fd);
const char* name;
while (reader.GetNextEntry(&name)) {
int i;
if (my_strtoui(&i, name) && i > 2 && i != fd)
IGNORE_RET(sys_close(i));
reader.PopEntry();
}
IGNORE_RET(sys_close(fd));
}
IGNORE_RET(sys_setsid());
// Leave one end of a pipe in the upload process and watch for it getting
// closed by the upload process exiting.
int fds[2];
if (sys_pipe(fds) >= 0) {
const pid_t upload_child = sys_fork();
if (!upload_child) {
// Upload process.
IGNORE_RET(sys_close(fds[0]));
IGNORE_RET(sys_dup2(fds[1], 3));
ExecUploadProcessOrTerminate(info, temp_file, mime_boundary, exe_buf,
&allocator);
}
// Helper process.
if (upload_child > 0) {
IGNORE_RET(sys_close(fds[1]));
char id_buf[17]; // Crash report IDs are expected to be 16 chars.
ssize_t len = -1;
// Upload should finish in about 10 seconds. Add a few more 500 ms
// internals to account for process startup time.
for (size_t wait_count = 0; wait_count < 24; ++wait_count) {
struct kernel_pollfd poll_fd;
poll_fd.fd = fds[0];
poll_fd.events = POLLIN | POLLPRI | POLLERR;
int ret = sys_poll(&poll_fd, 1, 500);
if (ret < 0) {
// Error
break;
} else if (ret > 0) {
// There is data to read.
len = HANDLE_EINTR(sys_read(fds[0], id_buf, sizeof(id_buf) - 1));
break;
}
// ret == 0 -> timed out, continue waiting.
}
if (len > 0) {
// Write crash dump id to stderr.
id_buf[len] = 0;
static const char msg[] = "\nCrash dump id: ";
WriteLog(msg, sizeof(msg) - 1);
WriteLog(id_buf, my_strlen(id_buf));
WriteLog("\n", 1);
}
if (sys_waitpid(upload_child, NULL, WNOHANG) == 0) {
// Upload process is still around, kill it.
sys_kill(upload_child, SIGKILL);
}
}
}
// Helper process.
IGNORE_RET(sys_unlink(info.filename));
IGNORE_RET(sys_unlink(temp_file));
sys__exit(0);
}
// Main browser process.
if (child <= 0)
return;
(void) HANDLE_EINTR(sys_waitpid(child, NULL, 0));
}
size_t WriteLog(const char* buf, size_t nbytes) {
return sys_write(2, buf, nbytes);
}
} // namespace crash_reporter

View file

@ -0,0 +1,38 @@
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_
#define ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_
#include "base/basictypes.h"
#include "vendor/breakpad/src/common/simple_string_dictionary.h"
namespace crash_reporter {
typedef google_breakpad::NonAllocatingMap<256, 256, 64> CrashKeyStorage;
// BreakpadInfo describes a crash report.
// The minidump information can either be contained in a file descriptor (fd) or
// in a file (whose path is in filename).
struct BreakpadInfo {
int fd; // File descriptor to the Breakpad dump data.
const char* filename; // Path to the Breakpad dump data.
const char* distro; // Linux distro string.
unsigned distro_length; // Length of |distro|.
bool upload; // Whether to upload or save crash dump.
uint64_t process_start_time; // Uptime of the crashing process.
size_t oom_size; // Amount of memory requested if OOM.
uint64_t pid; // PID where applicable.
const char* upload_url; // URL to upload the minidump.
CrashKeyStorage* crash_keys;
};
void HandleCrashDump(const BreakpadInfo& info);
size_t WriteLog(const char* buf, size_t nbytes);
} // namespace crash_reporter
#endif // ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_

View file

@ -0,0 +1,490 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/win/crash_service.h"
#include <windows.h>
#include <sddl.h>
#include <fstream> // NOLINT
#include <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/win/windows_version.h"
#include "vendor/breakpad/src/client/windows/crash_generation/client_info.h"
#include "vendor/breakpad/src/client/windows/crash_generation/crash_generation_server.h"
#include "vendor/breakpad/src/client/windows/sender/crash_report_sender.h"
namespace breakpad {
namespace {
const wchar_t kTestPipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
const wchar_t kGoogleReportURL[] = L"https://clients2.google.com/cr/report";
const wchar_t kCheckPointFile[] = L"crash_checkpoint.txt";
typedef std::map<std::wstring, std::wstring> CrashMap;
bool CustomInfoToMap(const google_breakpad::ClientInfo* client_info,
const std::wstring& reporter_tag, CrashMap* map) {
google_breakpad::CustomClientInfo info = client_info->GetCustomInfo();
for (uintptr_t i = 0; i < info.count; ++i) {
(*map)[info.entries[i].name] = info.entries[i].value;
}
(*map)[L"rept"] = reporter_tag;
return !map->empty();
}
bool WriteCustomInfoToFile(const std::wstring& dump_path, const CrashMap& map) {
std::wstring file_path(dump_path);
size_t last_dot = file_path.rfind(L'.');
if (last_dot == std::wstring::npos)
return false;
file_path.resize(last_dot);
file_path += L".txt";
std::wofstream file(file_path.c_str(),
std::ios_base::out | std::ios_base::app | std::ios::binary);
if (!file.is_open())
return false;
CrashMap::const_iterator pos;
for (pos = map.begin(); pos != map.end(); ++pos) {
std::wstring line = pos->first;
line += L':';
line += pos->second;
line += L'\n';
file.write(line.c_str(), static_cast<std::streamsize>(line.length()));
}
return true;
}
// The window procedure task is to handle when a) the user logs off.
// b) the system shuts down or c) when the user closes the window.
LRESULT __stdcall CrashSvcWndProc(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_CLOSE:
case WM_ENDSESSION:
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
return 0;
}
// This is the main and only application window.
HWND g_top_window = NULL;
bool CreateTopWindow(HINSTANCE instance, bool visible) {
WNDCLASSEXW wcx = {0};
wcx.cbSize = sizeof(wcx);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = CrashSvcWndProc;
wcx.hInstance = instance;
wcx.lpszClassName = L"crash_svc_class";
ATOM atom = ::RegisterClassExW(&wcx);
DWORD style = visible ? WS_POPUPWINDOW | WS_VISIBLE : WS_OVERLAPPED;
// The window size is zero but being a popup window still shows in the
// task bar and can be closed using the system menu or using task manager.
HWND window = CreateWindowExW(0, wcx.lpszClassName, L"crash service", style,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,
NULL, NULL, instance, NULL);
if (!window)
return false;
::UpdateWindow(window);
VLOG(1) << "window handle is " << window;
g_top_window = window;
return true;
}
// Simple helper class to keep the process alive until the current request
// finishes.
class ProcessingLock {
public:
ProcessingLock() {
::InterlockedIncrement(&op_count_);
}
~ProcessingLock() {
::InterlockedDecrement(&op_count_);
}
static bool IsWorking() {
return (op_count_ != 0);
}
private:
static volatile LONG op_count_;
};
volatile LONG ProcessingLock::op_count_ = 0;
// This structure contains the information that the worker thread needs to
// send a crash dump to the server.
struct DumpJobInfo {
DWORD pid;
CrashService* self;
CrashMap map;
std::wstring dump_path;
DumpJobInfo(DWORD process_id, CrashService* service,
const CrashMap& crash_map, const std::wstring& path)
: pid(process_id), self(service), map(crash_map), dump_path(path) {
}
};
} // namespace
// Command line switches:
const char CrashService::kMaxReports[] = "max-reports";
const char CrashService::kNoWindow[] = "no-window";
const char CrashService::kReporterTag[] = "reporter";
const char CrashService::kDumpsDir[] = "dumps-dir";
const char CrashService::kPipeName[] = "pipe-name";
const char CrashService::kReporterURL[] = "reporter-url";
CrashService::CrashService()
: sender_(NULL),
dumper_(NULL),
requests_handled_(0),
requests_sent_(0),
clients_connected_(0),
clients_terminated_(0) {
}
CrashService::~CrashService() {
base::AutoLock lock(sending_);
delete dumper_;
delete sender_;
}
bool CrashService::Initialize(const base::FilePath& operating_dir,
const base::FilePath& dumps_path) {
using google_breakpad::CrashReportSender;
using google_breakpad::CrashGenerationServer;
std::wstring pipe_name = kTestPipeName;
int max_reports = -1;
// The checkpoint file allows CrashReportSender to enforce the the maximum
// reports per day quota. Does not seem to serve any other purpose.
base::FilePath checkpoint_path = operating_dir.Append(kCheckPointFile);
CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
base::FilePath dumps_path_to_use = dumps_path;
if (cmd_line.HasSwitch(kDumpsDir)) {
dumps_path_to_use =
base::FilePath(cmd_line.GetSwitchValueNative(kDumpsDir));
}
// We can override the send reports quota with a command line switch.
if (cmd_line.HasSwitch(kMaxReports))
max_reports = _wtoi(cmd_line.GetSwitchValueNative(kMaxReports).c_str());
// Allow the global pipe name to be overridden for better testability.
if (cmd_line.HasSwitch(kPipeName))
pipe_name = cmd_line.GetSwitchValueNative(kPipeName);
if (max_reports > 0) {
// Create the http sender object.
sender_ = new CrashReportSender(checkpoint_path.value());
sender_->set_max_reports_per_day(max_reports);
}
SECURITY_ATTRIBUTES security_attributes = {0};
SECURITY_ATTRIBUTES* security_attributes_actual = NULL;
if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
SECURITY_DESCRIPTOR* security_descriptor =
reinterpret_cast<SECURITY_DESCRIPTOR*>(
GetSecurityDescriptorForLowIntegrity());
DCHECK(security_descriptor != NULL);
security_attributes.nLength = sizeof(security_attributes);
security_attributes.lpSecurityDescriptor = security_descriptor;
security_attributes.bInheritHandle = FALSE;
security_attributes_actual = &security_attributes;
}
// Create the OOP crash generator object.
dumper_ = new CrashGenerationServer(pipe_name, security_attributes_actual,
&CrashService::OnClientConnected, this,
&CrashService::OnClientDumpRequest, this,
&CrashService::OnClientExited, this,
NULL, NULL,
true, &dumps_path_to_use.value());
if (!dumper_) {
LOG(ERROR) << "could not create dumper";
if (security_attributes.lpSecurityDescriptor)
LocalFree(security_attributes.lpSecurityDescriptor);
return false;
}
if (!CreateTopWindow(::GetModuleHandleW(NULL),
!cmd_line.HasSwitch(kNoWindow))) {
LOG(ERROR) << "could not create window";
if (security_attributes.lpSecurityDescriptor)
LocalFree(security_attributes.lpSecurityDescriptor);
return false;
}
reporter_tag_ = L"crash svc";
if (cmd_line.HasSwitch(kReporterTag))
reporter_tag_ = cmd_line.GetSwitchValueNative(kReporterTag);
reporter_url_ = kGoogleReportURL;
if (cmd_line.HasSwitch(kReporterURL))
reporter_url_ = cmd_line.GetSwitchValueNative(kReporterURL);
// Log basic information.
VLOG(1) << "pipe name is " << pipe_name
<< "\ndumps at " << dumps_path_to_use.value();
if (sender_) {
VLOG(1) << "checkpoint is " << checkpoint_path.value()
<< "\nserver is " << reporter_url_
<< "\nmaximum " << sender_->max_reports_per_day() << " reports/day"
<< "\nreporter is " << reporter_tag_;
}
// Start servicing clients.
if (!dumper_->Start()) {
LOG(ERROR) << "could not start dumper";
if (security_attributes.lpSecurityDescriptor)
LocalFree(security_attributes.lpSecurityDescriptor);
return false;
}
if (security_attributes.lpSecurityDescriptor)
LocalFree(security_attributes.lpSecurityDescriptor);
// Create or open an event to signal the browser process that the crash
// service is initialized.
HANDLE running_event =
::CreateEventW(NULL, TRUE, TRUE, L"g_atom_shell_crash_service");
// If the browser already had the event open, the CreateEvent call did not
// signal it. We need to do it manually.
::SetEvent(running_event);
return true;
}
void CrashService::OnClientConnected(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
VLOG(1) << "client start. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_connected_);
}
void CrashService::OnClientExited(void* context,
const google_breakpad::ClientInfo* client_info) {
ProcessingLock lock;
VLOG(1) << "client end. pid = " << client_info->pid();
CrashService* self = static_cast<CrashService*>(context);
::InterlockedIncrement(&self->clients_terminated_);
if (!self->sender_)
return;
// When we are instructed to send reports we need to exit if there are
// no more clients to service. The next client that runs will start us.
// Only chrome.exe starts crash_service with a non-zero max_reports.
if (self->clients_connected_ > self->clients_terminated_)
return;
if (self->sender_->max_reports_per_day() > 0) {
// Wait for the other thread to send crashes, if applicable. The sender
// thread takes the sending_ lock, so the sleep is just to give it a
// chance to start.
::Sleep(1000);
base::AutoLock lock(self->sending_);
// Some people can restart chrome very fast, check again if we have
// a new client before exiting for real.
if (self->clients_connected_ == self->clients_terminated_) {
VLOG(1) << "zero clients. exiting";
::PostMessage(g_top_window, WM_CLOSE, 0, 0);
}
}
}
void CrashService::OnClientDumpRequest(void* context,
const google_breakpad::ClientInfo* client_info,
const std::wstring* file_path) {
ProcessingLock lock;
if (!file_path) {
LOG(ERROR) << "dump with no file path";
return;
}
if (!client_info) {
LOG(ERROR) << "dump with no client info";
return;
}
CrashService* self = static_cast<CrashService*>(context);
if (!self) {
LOG(ERROR) << "dump with no context";
return;
}
CrashMap map;
CustomInfoToMap(client_info, self->reporter_tag_, &map);
// Move dump file to the directory under client breakpad dump location.
base::FilePath dump_location = base::FilePath(*file_path);
CrashMap::const_iterator it = map.find(L"breakpad-dump-location");
if (it != map.end()) {
base::FilePath alternate_dump_location = base::FilePath(it->second);
file_util::CreateDirectoryW(alternate_dump_location);
alternate_dump_location = alternate_dump_location.Append(
dump_location.BaseName());
base::Move(dump_location, alternate_dump_location);
dump_location = alternate_dump_location;
}
DWORD pid = client_info->pid();
VLOG(1) << "dump for pid = " << pid << " is " << dump_location.value();
if (!WriteCustomInfoToFile(dump_location.value(), map)) {
LOG(ERROR) << "could not write custom info file";
}
if (!self->sender_)
return;
// Send the crash dump using a worker thread. This operation has retry
// logic in case there is no internet connection at the time.
DumpJobInfo* dump_job = new DumpJobInfo(pid, self, map,
dump_location.value());
if (!::QueueUserWorkItem(&CrashService::AsyncSendDump,
dump_job, WT_EXECUTELONGFUNCTION)) {
LOG(ERROR) << "could not queue job";
}
}
// We are going to try sending the report several times. If we can't send,
// we sleep from one minute to several hours depending on the retry round.
DWORD CrashService::AsyncSendDump(void* context) {
if (!context)
return 0;
DumpJobInfo* info = static_cast<DumpJobInfo*>(context);
std::wstring report_id = L"<unsent>";
const DWORD kOneMinute = 60*1000;
const DWORD kOneHour = 60*kOneMinute;
const DWORD kSleepSchedule[] = {
24*kOneHour,
8*kOneHour,
4*kOneHour,
kOneHour,
15*kOneMinute,
0};
int retry_round = arraysize(kSleepSchedule) - 1;
do {
::Sleep(kSleepSchedule[retry_round]);
{
// Take the server lock while sending. This also prevent early
// termination of the service object.
base::AutoLock lock(info->self->sending_);
VLOG(1) << "trying to send report for pid = " << info->pid;
google_breakpad::ReportResult send_result
= info->self->sender_->SendCrashReport(info->self->reporter_url_,
info->map,
info->dump_path,
&report_id);
switch (send_result) {
case google_breakpad::RESULT_FAILED:
report_id = L"<network issue>";
break;
case google_breakpad::RESULT_REJECTED:
report_id = L"<rejected>";
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_SUCCEEDED:
++info->self->requests_sent_;
++info->self->requests_handled_;
retry_round = 0;
break;
case google_breakpad::RESULT_THROTTLED:
report_id = L"<throttled>";
break;
default:
report_id = L"<unknown>";
break;
};
}
VLOG(1) << "dump for pid =" << info->pid << " crash2 id =" << report_id;
--retry_round;
} while (retry_round >= 0);
if (!::DeleteFileW(info->dump_path.c_str()))
LOG(WARNING) << "could not delete " << info->dump_path;
delete info;
return 0;
}
int CrashService::ProcessingLoop() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
VLOG(1) << "session ending..";
while (ProcessingLock::IsWorking()) {
::Sleep(50);
}
VLOG(1) << "clients connected :" << clients_connected_
<< "\nclients terminated :" << clients_terminated_
<< "\ndumps serviced :" << requests_handled_
<< "\ndumps reported :" << requests_sent_;
return static_cast<int>(msg.wParam);
}
PSECURITY_DESCRIPTOR CrashService::GetSecurityDescriptorForLowIntegrity() {
// Build the SDDL string for the label.
std::wstring sddl = L"S:(ML;;NW;;;S-1-16-4096)";
DWORD error = ERROR_SUCCESS;
PSECURITY_DESCRIPTOR sec_desc = NULL;
PACL sacl = NULL;
BOOL sacl_present = FALSE;
BOOL sacl_defaulted = FALSE;
if (::ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),
SDDL_REVISION,
&sec_desc, NULL)) {
if (::GetSecurityDescriptorSacl(sec_desc, &sacl_present, &sacl,
&sacl_defaulted)) {
return sec_desc;
}
}
return NULL;
}
} // namespace breakpad

View file

@ -0,0 +1,131 @@
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_H_
#define COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_H_
#include <string>
#include "base/basictypes.h"
#include "base/files/file_path.h"
#include "base/synchronization/lock.h"
namespace google_breakpad {
class CrashReportSender;
class CrashGenerationServer;
class ClientInfo;
}
namespace breakpad {
// This class implements an out-of-process crash server. It uses breakpad's
// CrashGenerationServer and CrashReportSender to generate and then send the
// crash dumps. Internally, it uses OS specific pipe to allow applications to
// register for crash dumps and later on when a registered application crashes
// it will signal an event that causes this code to wake up and perform a
// crash dump on the signaling process. The dump is then stored on disk and
// possibly sent to the crash2 servers.
class CrashService {
public:
CrashService();
~CrashService();
// Starts servicing crash dumps. Returns false if it failed. Do not use
// other members in that case. |operating_dir| is where the CrashService
// should store breakpad's checkpoint file. |dumps_path| is the directory
// where the crash dumps should be stored.
bool Initialize(const base::FilePath& operating_dir,
const base::FilePath& dumps_path);
// Command line switches:
//
// --max-reports=<number>
// Allows to override the maximum number for reports per day. Normally
// the crash dumps are never sent so if you want to send any you must
// specify a positive number here.
static const char kMaxReports[];
// --no-window
// Does not create a visible window on the desktop. The window does not have
// any other functionality other than allowing the crash service to be
// gracefully closed.
static const char kNoWindow[];
// --reporter=<string>
// Allows to specify a custom string that appears on the detail crash report
// page in the crash server. This should be a 25 chars or less string.
// The default tag if not specified is 'crash svc'.
static const char kReporterTag[];
// --dumps-dir=<directory-path>
// Override the directory to which crash dump files will be written.
static const char kDumpsDir[];
// --pipe-name=<string>
// Override the name of the Windows named pipe on which we will
// listen for crash dump request messages.
static const char kPipeName[];
// --reporter-url=<string>
// Override the URL to which crash reports will be sent to.
static const char kReporterURL[];
// Returns number of crash dumps handled.
int requests_handled() const {
return requests_handled_;
}
// Returns number of crash clients registered.
int clients_connected() const {
return clients_connected_;
}
// Returns number of crash clients terminated.
int clients_terminated() const {
return clients_terminated_;
}
// Starts the processing loop. This function does not return unless the
// user is logging off or the user closes the crash service window. The
// return value is a good number to pass in ExitProcess().
int ProcessingLoop();
private:
static void OnClientConnected(void* context,
const google_breakpad::ClientInfo* client_info);
static void OnClientDumpRequest(
void* context,
const google_breakpad::ClientInfo* client_info,
const std::wstring* file_path);
static void OnClientExited(void* context,
const google_breakpad::ClientInfo* client_info);
// This routine sends the crash dump to the server. It takes the sending_
// lock when it is performing the send.
static DWORD __stdcall AsyncSendDump(void* context);
// Returns the security descriptor which access to low integrity processes
// The caller is supposed to free the security descriptor by calling
// LocalFree.
PSECURITY_DESCRIPTOR GetSecurityDescriptorForLowIntegrity();
google_breakpad::CrashGenerationServer* dumper_;
google_breakpad::CrashReportSender* sender_;
// the extra tag sent to the server with each dump.
std::wstring reporter_tag_;
// receiver URL of crash reports.
std::wstring reporter_url_;
// clients serviced statistics:
int requests_handled_;
int requests_sent_;
volatile LONG clients_connected_;
volatile LONG clients_terminated_;
base::Lock sending_;
DISALLOW_COPY_AND_ASSIGN(CrashService);
};
} // namespace breakpad
#endif // COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_H_

View file

@ -0,0 +1,92 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "atom/common/crash_reporter/win/crash_service_main.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "atom/common/crash_reporter/win/crash_service.h"
namespace crash_service {
namespace {
const char kApplicationName[] = "application-name";
const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service";
const wchar_t kStandardLogFile[] = L"operation_log.txt";
bool GetCrashServiceDirectory(const std::wstring& application_name,
base::FilePath* dir) {
base::FilePath temp_dir;
if (!file_util::GetTempDir(&temp_dir))
return false;
temp_dir = temp_dir.Append(application_name + L" Crashes");
if (!base::PathExists(temp_dir)) {
if (!file_util::CreateDirectory(temp_dir))
return false;
}
*dir = temp_dir;
return true;
}
} // namespace.
int Main(const wchar_t* cmd) {
// Initialize all Chromium things.
base::AtExitManager exit_manager;
CommandLine::Init(0, NULL);
CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
// Use the application's name as pipe name and output directory.
if (!cmd_line.HasSwitch(kApplicationName)) {
LOG(ERROR) << "Application's name must be specified with --"
<< kApplicationName;
return 1;
}
std::wstring application_name = cmd_line.GetSwitchValueNative(
kApplicationName);
// We use/create a directory under the user's temp folder, for logging.
base::FilePath operating_dir;
GetCrashServiceDirectory(application_name, &operating_dir);
base::FilePath log_file = operating_dir.Append(kStandardLogFile);
// Logging to stderr (to help with debugging failures on the
// buildbots) and to a file.
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_ALL;
settings.log_file = log_file.value().c_str();
logging::InitLogging(settings);
// Logging with pid, tid and timestamp.
logging::SetLogItems(true, true, true, false);
VLOG(1) << "Session start. cmdline is [" << cmd << "]";
// Setting the crash reporter.
string16 pipe_name = ReplaceStringPlaceholders(kPipeNameFormat,
application_name,
NULL);
cmd_line.AppendSwitch("no-window");
cmd_line.AppendSwitchASCII("max-reports", "128");
cmd_line.AppendSwitchASCII("reporter", "atom-shell-crash-service");
cmd_line.AppendSwitchNative("pipe-name", pipe_name);
breakpad::CrashService crash_service;
if (!crash_service.Initialize(operating_dir, operating_dir))
return 2;
VLOG(1) << "Ready to process crash requests";
// Enter the message loop.
int retv = crash_service.ProcessingLoop();
// Time to exit.
VLOG(1) << "Session end. return code is " << retv;
return retv;
}
} // namespace crash_service

View file

@ -0,0 +1,15 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_MAIN_H_
#define COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_MAIN_H_
namespace crash_service {
// Program entry, should be called by main();
int Main(const wchar_t* cmd_line);
} // namespace crash_service
#endif // COMMON_CRASH_REPORTER_WIN_CRASH_SERVICE_MAIN_H_