Start invoking core2md to implement full system crash reporting

BUG=4741

Review URL: http://codereview.chromium.org/3040013
diff --git a/crash_reporter/Makefile b/crash_reporter/Makefile
index ccd39be..ae72a6d 100644
--- a/crash_reporter/Makefile
+++ b/crash_reporter/Makefile
@@ -19,7 +19,7 @@
 all: $(REPORTER_BINS)
 
 $(CRASH_REPORTER): crash_reporter.o $(CRASH_OBJS)
-	$(CXX) $(CXXFLAGS) $^ -lcrash $(REPORTER_LIBS) -o $@
+	$(CXX) $(CXXFLAGS) $^ $(REPORTER_LIBS) -o $@
 
 tests: $(TEST_BINS)
 
diff --git a/crash_reporter/crash_reporter.cc b/crash_reporter/crash_reporter.cc
index 80494cc..0930cea 100644
--- a/crash_reporter/crash_reporter.cc
+++ b/crash_reporter/crash_reporter.cc
@@ -16,22 +16,22 @@
 DEFINE_bool(init, false, "Initialize crash logging");
 DEFINE_bool(clean_shutdown, false, "Signal clean shutdown");
 DEFINE_bool(crash_test, false, "Crash test");
-DEFINE_string(exec, "", "Executable name crashed");
 DEFINE_int32(pid, -1, "Crashing PID");
 DEFINE_int32(signal, -1, "Signal causing crash");
 DEFINE_bool(unclean_check, true, "Check for unclean shutdown");
 #pragma GCC diagnostic error "-Wstrict-aliasing"
 
 static const char kCrashCounterHistogram[] = "Logging.CrashCounter";
+static const char kEmpty[] = "";
 static const char kUncleanShutdownFile[] =
     "/var/lib/crash_reporter/pending_clean_shutdown";
-static const char kEmpty[] = "";
+
 
 // Enumeration of kinds of crashes to be used in the CrashCounter histogram.
 enum CrashKinds {
-  CRASH_KIND_KERNEL = 1,
-  CRASH_KIND_USER   = 2,
-  CRASH_KIND_MAX
+  kCrashKindKernel = 1,
+  kCrashKindUser   = 2,
+  kCrashKindMax
 };
 
 static MetricsLibrary s_metrics_lib;
@@ -52,8 +52,8 @@
   s_system_log.LogWarning("Last shutdown was not clean");
   if (IsMetricsCollectionAllowed()) {
     s_metrics_lib.SendEnumToUMA(std::string(kCrashCounterHistogram),
-                                CRASH_KIND_KERNEL,
-                                CRASH_KIND_MAX);
+                                kCrashKindKernel,
+                                kCrashKindMax);
   }
   if (!file_util::Delete(unclean_file_path, false)) {
     s_system_log.LogError("Failed to delete unclean shutdown file %s",
@@ -82,8 +82,8 @@
 static void CountUserCrash() {
   CHECK(IsMetricsCollectionAllowed());
   s_metrics_lib.SendEnumToUMA(std::string(kCrashCounterHistogram),
-                              CRASH_KIND_USER,
-                              CRASH_KIND_MAX);
+                              kCrashKindUser,
+                              kCrashKindMax);
 
   // Announce through D-Bus whenever a user crash happens. This is
   // used by the metrics daemon to log active use time between
@@ -108,7 +108,8 @@
   user_collector.Initialize(CountUserCrash,
                             my_path.value(),
                             IsMetricsCollectionAllowed,
-                            &s_system_log);
+                            &s_system_log,
+                            true);  // generate_diagnostics
 
   if (FLAGS_init) {
     CHECK(!FLAGS_clean_shutdown) << "Incompatible options";
@@ -131,7 +132,6 @@
   // Handle a specific user space crash.
   CHECK(FLAGS_signal != -1) << "Signal must be set";
   CHECK(FLAGS_pid != -1) << "PID must be set";
-  CHECK(FLAGS_exec != "") << "Executable name must be set";
 
   // Make it possible to test what happens when we crash while
   // handling a crash.
@@ -140,7 +140,10 @@
     return 0;
   }
 
-  user_collector.HandleCrash(FLAGS_signal, FLAGS_pid, FLAGS_exec);
+  // Handle the crash, get the name of the process from procfs.
+  if (!user_collector.HandleCrash(FLAGS_signal, FLAGS_pid, NULL)) {
+    return 1;
+  }
 
   return 0;
 }
diff --git a/crash_reporter/crash_sender b/crash_reporter/crash_sender
index 90cd661..6da8933 100644
--- a/crash_reporter/crash_sender
+++ b/crash_reporter/crash_sender
@@ -46,13 +46,8 @@
   logger -t "${TAG}" "$@"
 }
 
-log_done() {
-  lecho "Done"
-}
-
 cleanup_tmp_dir() {
   rm -rf "${TMP_DIR}"
-  log_done
 }
 
 cleanup_run_file_and_tmp_dir() {
@@ -119,6 +114,12 @@
   return 0
 }
 
+# Return if $1 is a .core file
+is_core_file() {
+  local filename=$1
+  [ "${filename##*.}" = "core" ]
+}
+
 send_crash() {
   local sleep_time=$(generate_uniform_random $SECONDS_SEND_SPREAD)
   local url="${MINIDUMP_UPLOAD_STAGING_URL}"
@@ -183,6 +184,7 @@
 send_crashes() {
   local dir="$1"
   lecho "Considering crashes in ${dir}"
+
   # Cycle through minidumps, most recent first.  That way if we're about
   # to exceed the daily rate, we send the most recent minidumps.
   if [ ! -d "${dir}" ]; then
@@ -190,11 +192,15 @@
   fi
   for file in $(ls -1t "${dir}"); do
     local minidump_path="${dir}/${file}"
-    lecho "Considering crash ${minidump_path}"
+    lecho "Considering file ${minidump_path}"
+    if is_core_file "${minidump_path}"; then
+      lecho "Ignoring core file."
+      continue
+    fi
     if ! check_rate; then
       lecho "Sending ${minidump_path} would exceed rate.  Leaving for later."
       return 0
-   fi
+    fi
     local chromeos_version=$(get_version)
     if is_feedback_disabled; then
       lecho "Uploading is disabled.  Removing crash."
@@ -212,9 +218,6 @@
 }
 
 main() {
-  lecho "Starting"
-  trap log_done EXIT INT
-
   if [ -e "${PAUSE_CRASH_SENDING}" ]; then
     lecho "Exiting early due to ${PAUSE_CRASH_SENDING}"
     exit 1
diff --git a/crash_reporter/system_logging.h b/crash_reporter/system_logging.h
index 8c946b0..7ebfc5e 100644
--- a/crash_reporter/system_logging.h
+++ b/crash_reporter/system_logging.h
@@ -2,8 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef CRASH_SYSTEM_LOGGING_H_
-#define CRASH_SYSTEM_LOGGING_H_
+#ifndef CRASH_REPORTER_SYSTEM_LOGGING_H_
+#define CRASH_REPORTER_SYSTEM_LOGGING_H_
 
 #include <string>
 
@@ -27,4 +27,4 @@
   static std::string identity_;
 };
 
-#endif  // CRASH_SYSTEM_LOGGING_H_
+#endif  // CRASH_REPORTER_SYSTEM_LOGGING_H_
diff --git a/crash_reporter/system_logging_mock.h b/crash_reporter/system_logging_mock.h
index 191e531..639fe42 100644
--- a/crash_reporter/system_logging_mock.h
+++ b/crash_reporter/system_logging_mock.h
@@ -2,8 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef CRASH_SYSTEM_LOGGING_MOCK_H_
-#define CRASH_SYSTEM_LOGGING_MOCK_H_
+#ifndef CRASH_REPORTER_SYSTEM_LOGGING_MOCK_H_
+#define CRASH_REPORTER_SYSTEM_LOGGING_MOCK_H_
 
 #include <string>
 
@@ -24,4 +24,4 @@
   std::string ident_;
 };
 
-#endif  // CRASH_SYSTEM_LOGGING_H_
+#endif  // CRASH_REPORTER_SYSTEM_LOGGING_H_
diff --git a/crash_reporter/user_collector.cc b/crash_reporter/user_collector.cc
index 918f691..7af35ce 100644
--- a/crash_reporter/user_collector.cc
+++ b/crash_reporter/user_collector.cc
@@ -2,6 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include <grp.h>  // For struct group.
+#include <pwd.h>  // For struct passwd.
+#include <sys/types.h>  // For getpwuid_r and getgrnam_r.
+
 #include <string>
 
 #include "base/file_util.h"
@@ -14,9 +18,27 @@
 // instead pipe the core file into a user space process.  See
 // core(5) man page.
 static const char kCorePatternFile[] = "/proc/sys/kernel/core_pattern";
+static const char kCoreToMinidumpConverterPath[] = "/usr/bin/core2md";
+static const char kDefaultUserName[] = "chronos";
+static const char kLeaveCoreFile[] = "/etc/leave_core";
+static const char kSystemCrashPath[] = "/var/spool/crash";
+static const char kUserCrashPath[] = "/home/chronos/user/crash";
+
+// Directory mode of the user crash spool directory.
+static const mode_t kUserCrashPathMode = 0755;
+
+// Directory mode of the system crash spool directory.
+static const mode_t kSystemCrashPathMode = 01755;
+
+static const uid_t kRootOwner = 0;
+static const uid_t kRootGroup = 0;
+
+const char *UserCollector::kUserId = "Uid:\t";
+const char *UserCollector::kGroupId = "Gid:\t";
 
 UserCollector::UserCollector()
-    : core_pattern_file_(kCorePatternFile),
+    : generate_diagnostics_(false),
+      core_pattern_file_(kCorePatternFile),
       count_crash_function_(NULL),
       initialized_(false),
       is_feedback_allowed_function_(NULL),
@@ -27,7 +49,8 @@
     UserCollector::CountCrashFunction count_crash_function,
     const std::string &our_path,
     UserCollector::IsFeedbackAllowedFunction is_feedback_allowed_function,
-    SystemLogging *logger) {
+    SystemLogging *logger,
+    bool generate_diagnostics) {
   CHECK(count_crash_function != NULL);
   CHECK(is_feedback_allowed_function != NULL);
   CHECK(logger != NULL);
@@ -37,6 +60,7 @@
   is_feedback_allowed_function_ = is_feedback_allowed_function;
   logger_ = logger;
   initialized_ = true;
+  generate_diagnostics_ = generate_diagnostics;
 }
 
 UserCollector::~UserCollector() {
@@ -44,8 +68,7 @@
 
 std::string UserCollector::GetPattern(bool enabled) const {
   if (enabled) {
-    return StringPrintf("|%s --signal=%%s --pid=%%p --exec=%%e",
-                        our_path_.c_str());
+    return StringPrintf("|%s --signal=%%s --pid=%%p", our_path_.c_str());
   } else {
     return "core";
   }
@@ -65,12 +88,336 @@
   return true;
 }
 
-void UserCollector::HandleCrash(int signal, int pid, const std::string &exec) {
+FilePath UserCollector::GetProcessPath(pid_t pid) {
+  return FilePath(StringPrintf("/proc/%d", pid));
+}
+
+bool UserCollector::GetSymlinkTarget(const FilePath &symlink,
+                                     FilePath *target) {
+  int max_size = 32;
+  scoped_array<char> buffer;
+  while (true) {
+    buffer.reset(new char[max_size + 1]);
+    ssize_t size = readlink(symlink.value().c_str(), buffer.get(), max_size);
+    if (size < 0) {
+      return false;
+    }
+    buffer[size] = 0;
+    if (size == max_size) {
+      // Avoid overflow when doubling.
+      if (max_size * 2 > max_size) {
+        max_size *= 2;
+        continue;
+      } else {
+        return false;
+      }
+    }
+    break;
+  }
+
+  *target = FilePath(buffer.get());
+  return true;
+}
+
+bool UserCollector::GetExecutableBaseNameFromPid(uid_t pid,
+                                                 std::string *base_name) {
+  FilePath target;
+  if (!GetSymlinkTarget(GetProcessPath(pid).Append("exe"), &target))
+    return false;
+  *base_name = target.BaseName().value();
+  return true;
+}
+
+bool UserCollector::GetIdFromStatus(const char *prefix,
+                                    IdKind kind,
+                                    const std::string &status_contents,
+                                    int *id) {
+  // From fs/proc/array.c:task_state(), this file contains:
+  // \nUid:\t<uid>\t<euid>\t<suid>\t<fsuid>\n
+  std::vector<std::string> status_lines;
+  SplitString(status_contents, '\n', &status_lines);
+  std::vector<std::string>::iterator line_iterator;
+  for (line_iterator = status_lines.begin();
+       line_iterator != status_lines.end();
+       ++line_iterator) {
+    if (line_iterator->find(prefix) == 0)
+      break;
+  }
+  if (line_iterator == status_lines.end()) {
+    return false;
+  }
+  std::string id_substring = line_iterator->substr(strlen(prefix),
+                                                   std::string::npos);
+  std::vector<std::string> ids;
+  SplitString(id_substring, '\t', &ids);
+  if (ids.size() != kIdMax || kind < 0 || kind >= kIdMax) {
+    return false;
+  }
+  const char *number = ids[kind].c_str();
+  char *end_number = NULL;
+  *id = strtol(number, &end_number, 10);
+  if (*end_number != '\0')
+    return false;
+  return true;
+}
+
+bool UserCollector::GetUserInfoFromName(const std::string &name,
+                                        uid_t *uid,
+                                        gid_t *gid) {
+  char storage[256];
+  struct passwd passwd_storage;
+  struct passwd *passwd_result = NULL;
+
+  if (getpwnam_r(name.c_str(), &passwd_storage, storage, sizeof(storage),
+                 &passwd_result) != 0 || passwd_result == NULL) {
+    logger_->LogError("Cannot find user named %s", name.c_str());
+    return false;
+  }
+
+  *uid = passwd_result->pw_uid;
+  *gid = passwd_result->pw_gid;
+  return true;
+}
+
+bool UserCollector::CopyOffProcFiles(pid_t pid,
+                                     const FilePath &container_dir) {
+  if (!file_util::CreateDirectory(container_dir)) {
+    logger_->LogInfo("Could not create %s", container_dir.value().c_str());
+    return false;
+  }
+  FilePath process_path = GetProcessPath(pid);
+  if (!file_util::PathExists(process_path)) {
+    logger_->LogWarning("Path %s does not exist",
+                        process_path.value().c_str());
+    return false;
+  }
+  static const char *proc_files[] = {
+    "auxv",
+    "cmdline",
+    "environ",
+    "maps",
+    "status"
+  };
+  for (unsigned i = 0; i < arraysize(proc_files); ++i) {
+    if (!file_util::CopyFile(process_path.Append(proc_files[i]),
+                             container_dir.Append(proc_files[i]))) {
+      logger_->LogWarning("Could not copy %s file", proc_files[i]);
+      return false;
+    }
+  }
+  return true;
+}
+
+FilePath UserCollector::GetCrashDirectoryInfo(
+    uid_t process_euid,
+    uid_t default_user_id,
+    gid_t default_user_group,
+    mode_t *mode,
+    uid_t *directory_owner,
+    gid_t *directory_group) {
+  if (process_euid == default_user_id) {
+    *mode = kUserCrashPathMode;
+    *directory_owner = default_user_id;
+    *directory_group = default_user_group;
+    return FilePath(kUserCrashPath);
+  } else {
+    *mode = kSystemCrashPathMode;
+    *directory_owner = kRootOwner;
+    *directory_group = kRootGroup;
+    return FilePath(kSystemCrashPath);
+  }
+}
+
+bool UserCollector::GetCreatedCrashDirectory(pid_t pid,
+                                             FilePath *crash_file_path) {
+  FilePath process_path = GetProcessPath(pid);
+  std::string status;
+  if (!file_util::ReadFileToString(process_path.Append("status"),
+                                   &status)) {
+    logger_->LogError("Could not read status file");
+    return false;
+  }
+  int process_euid;
+  if (!GetIdFromStatus(kUserId, kIdEffective, status, &process_euid)) {
+    logger_->LogError("Could not find euid in status file");
+    return false;
+  }
+  uid_t default_user_id;
+  gid_t default_user_group;
+  if (!GetUserInfoFromName(kDefaultUserName,
+                           &default_user_id,
+                           &default_user_group)) {
+    logger_->LogError("Could not find default user info");
+    return false;
+  }
+  mode_t directory_mode;
+  uid_t directory_owner;
+  gid_t directory_group;
+  *crash_file_path =
+      GetCrashDirectoryInfo(process_euid,
+                            default_user_id,
+                            default_user_group,
+                            &directory_mode,
+                            &directory_owner,
+                            &directory_group);
+
+
+  if (!file_util::PathExists(*crash_file_path)) {
+    // Create the spool directory with the appropriate mode (regardless of
+    // umask) and ownership.
+    mode_t old_mask = umask(0);
+    if (mkdir(crash_file_path->value().c_str(), directory_mode) < 0 ||
+        chown(crash_file_path->value().c_str(),
+              directory_owner,
+              directory_group) < 0) {
+      logger_->LogError("Unable to create appropriate crash directory");
+      return false;
+    }
+    umask(old_mask);
+  }
+
+  if (!file_util::PathExists(*crash_file_path)) {
+    logger_->LogError("Unable to create crash directory %s",
+                      crash_file_path->value().c_str());
+    return false;
+  }
+
+
+  return true;
+}
+
+std::string UserCollector::FormatDumpBasename(const std::string &exec_name,
+                                              time_t timestamp,
+                                              pid_t pid) {
+  struct tm tm;
+  localtime_r(&timestamp, &tm);
+  return StringPrintf("%s.%04d%02d%02d.%02d%02d%02d.%d",
+                      exec_name.c_str(),
+                      tm.tm_year + 1900,
+                      tm.tm_mon + 1,
+                      tm.tm_mday,
+                      tm.tm_hour,
+                      tm.tm_min,
+                      tm.tm_sec,
+                      pid);
+}
+
+bool UserCollector::CopyStdinToCoreFile(const FilePath &core_path) {
+  // Copy off all stdin to a core file.
+  FilePath stdin_path("/dev/fd/0");
+  if (file_util::CopyFile(stdin_path, core_path)) {
+    return true;
+  }
+
+  logger_->LogError("Could not write core file");
+  // If the file system was full, make sure we remove any remnants.
+  file_util::Delete(core_path, false);
+  return false;
+}
+
+bool UserCollector::ConvertCoreToMinidump(const FilePath &core_path,
+                                          const FilePath &procfs_directory,
+                                          const FilePath &minidump_path,
+                                          const FilePath &temp_directory) {
+  // TODO(kmixter): Rewrite to use process_util once it's included in
+  // libchrome.
+  FilePath output_path = temp_directory.Append("output");
+  std::string core2md_command =
+      StringPrintf("\"%s\" \"%s\" \"%s\" \"%s\" > \"%s\" 2>&1",
+                   kCoreToMinidumpConverterPath,
+                   core_path.value().c_str(),
+                   procfs_directory.value().c_str(),
+                   minidump_path.value().c_str(),
+                   output_path.value().c_str());
+  int errorlevel = system(core2md_command.c_str());
+
+  std::string output;
+  file_util::ReadFileToString(output_path, &output);
+  if (errorlevel != 0) {
+    logger_->LogInfo("Problem during %s [result=%d]: %s",
+                     core2md_command.c_str(),
+                     errorlevel,
+                     output.c_str());
+    return false;
+  }
+
+  if (!file_util::PathExists(minidump_path)) {
+    logger_->LogError("Minidump file %s was not created",
+                      minidump_path.value().c_str());
+    return false;
+  }
+  return true;
+}
+
+bool UserCollector::GenerateDiagnostics(pid_t pid,
+                                        const std::string &exec_name) {
+  FilePath container_dir("/tmp");
+  container_dir = container_dir.Append(
+      StringPrintf("crash_reporter.%d", pid));
+
+  if (!CopyOffProcFiles(pid, container_dir)) {
+    file_util::Delete(container_dir, true);
+    return false;
+  }
+
+  FilePath spool_path;
+  if (!GetCreatedCrashDirectory(pid, &spool_path)) {
+    file_util::Delete(container_dir, true);
+    return false;
+  }
+  std::string dump_basename = FormatDumpBasename(exec_name, time(NULL), pid);
+  FilePath core_path = spool_path.Append(
+      StringPrintf("%s.core", dump_basename.c_str()));
+
+  if (!CopyStdinToCoreFile(core_path)) {
+    file_util::Delete(container_dir, true);
+    return false;
+  }
+
+  FilePath minidump_path = spool_path.Append(
+      StringPrintf("%s.dmp", dump_basename.c_str()));
+
+  bool conversion_result = true;
+  if (!ConvertCoreToMinidump(core_path,
+                             container_dir,  // procfs directory
+                             minidump_path,
+                             container_dir)) {  // temporary directory
+    // Note we leave the container directory for inspection.
+    conversion_result = false;
+  }
+
+  if (conversion_result) {
+    logger_->LogInfo("Stored minidump to %s", minidump_path.value().c_str());
+  }
+
+  if (!file_util::PathExists(FilePath(kLeaveCoreFile))) {
+    file_util::Delete(core_path, false);
+  } else {
+    logger_->LogInfo("Leaving core file at %s", core_path.value().c_str());
+  }
+
+  return conversion_result;
+}
+
+bool UserCollector::HandleCrash(int signal, int pid, const char *force_exec) {
   CHECK(initialized_);
+  std::string exec;
+  if (force_exec) {
+    exec.assign(force_exec);
+  } else if (!GetExecutableBaseNameFromPid(pid, &exec)) {
+    // If for some reason we don't have the base name, avoid completely
+    // failing by indicating an unknown name.
+    exec = "unknown";
+  }
   logger_->LogWarning("Received crash notification for %s[%d] sig %d",
                       exec.c_str(), pid, signal);
 
   if (is_feedback_allowed_function_()) {
     count_crash_function_();
   }
+
+  if (generate_diagnostics_) {
+    return GenerateDiagnostics(pid, exec);
+  }
+  return true;
 }
diff --git a/crash_reporter/user_collector.h b/crash_reporter/user_collector.h
index 0d5dd01..dc633bb 100644
--- a/crash_reporter/user_collector.h
+++ b/crash_reporter/user_collector.h
@@ -2,12 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef _CRASH_USER_COLLECTOR_H_
-#define _CRASH_USER_COLLECTOR_H_
+#ifndef _CRASH_REPORTER_USER_COLLECTOR_H_
+#define _CRASH_REPORTER_USER_COLLECTOR_H_
 
 #include <string>
 
 #include "crash-reporter/system_logging.h"
+#include "gtest/gtest_prod.h"  // for FRIEND_TEST
 
 class FilePath;
 
@@ -22,12 +23,14 @@
   // Initialize the user crash collector for detection of crashes,
   // given a crash counting function, the path to this executable,
   // metrics collection enabled oracle, and system logger facility.
-  // Crash detection/reporting is not enabled until Enable is
-  // called.
+  // Crash detection/reporting is not enabled until Enable is called.
+  // |generate_diagnostics| is used to indicate whether or not to try
+  // to generate a minidump from crashes.
   void Initialize(CountCrashFunction count_crash,
                   const std::string &our_path,
                   IsFeedbackAllowedFunction is_metrics_allowed,
-                  SystemLogging *logger);
+                  SystemLogging *logger,
+                  bool generate_diagnostics);
 
   virtual ~UserCollector();
 
@@ -37,8 +40,8 @@
   // Disable collection.
   bool Disable() { return SetUpInternal(false); }
 
-  // Handle a specific user crash.
-  void HandleCrash(int signal, int pid, const std::string &exec);
+  // Handle a specific user crash.  Returns true on success.
+  bool HandleCrash(int signal, int pid, const char *force_exec);
 
   // Set (override the default) core file pattern.
   void set_core_pattern_file(const std::string &pattern) {
@@ -47,16 +50,74 @@
 
  private:
   friend class UserCollectorTest;
+  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesBadPath);
+  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesBadPid);
+  FRIEND_TEST(UserCollectorTest, CopyOffProcFilesOK);
+  FRIEND_TEST(UserCollectorTest, FormatDumpBasename);
+  FRIEND_TEST(UserCollectorTest, GetCrashDirectoryInfo);
+  FRIEND_TEST(UserCollectorTest, GetIdFromStatus);
+  FRIEND_TEST(UserCollectorTest, GetProcessPath);
+  FRIEND_TEST(UserCollectorTest, GetSymlinkTarget);
+  FRIEND_TEST(UserCollectorTest, GetUserInfoFromName);
+
+  // Enumeration to pass to GetIdFromStatus.  Must match the order
+  // that the kernel lists IDs in the status file.
+  enum IdKind {
+    kIdReal = 0,  // uid and gid
+    kIdEffective = 1,  // euid and egid
+    kIdSet = 2,  // suid and sgid
+    kIdFileSystem = 3,  // fsuid and fsgid
+    kIdMax
+  };
 
   std::string GetPattern(bool enabled) const;
   bool SetUpInternal(bool enabled);
 
+  FilePath GetProcessPath(pid_t pid);
+  bool GetSymlinkTarget(const FilePath &symlink,
+                        FilePath *target);
+  bool GetExecutableBaseNameFromPid(uid_t pid,
+                                    std::string *base_name);
+  bool GetIdFromStatus(const char *prefix,
+                       IdKind kind,
+                       const std::string &status_contents,
+                       int *id);
+  bool GetUserInfoFromName(const std::string &name,
+                           uid_t *uid,
+                           gid_t *gid);
+  bool CopyOffProcFiles(pid_t pid, const FilePath &process_map);
+  FilePath GetCrashDirectoryInfo(uid_t process_euid,
+                                 uid_t default_user_id,
+                                 gid_t default_user_group,
+                                 mode_t *mode,
+                                 uid_t *directory_owner,
+                                 gid_t *directory_group);
+  // Determines the crash directory for given pid based on pid's owner,
+  // and creates the directory if necessary with appropriate permissions.
+  // Returns true whether or not directory needed to be created, false on
+  // any failure.
+  bool GetCreatedCrashDirectory(pid_t pid,
+                                FilePath *crash_file_path);
+  std::string FormatDumpBasename(const std::string &exec_name,
+                                 time_t timestamp,
+                                 pid_t pid);
+  bool CopyStdinToCoreFile(const FilePath &core_path);
+  bool ConvertCoreToMinidump(const FilePath &core_path,
+                             const FilePath &procfs_directory,
+                             const FilePath &minidump_path,
+                             const FilePath &temp_directory);
+  bool GenerateDiagnostics(pid_t pid, const std::string &exec_name);
+
+  bool generate_diagnostics_;
   std::string core_pattern_file_;
   CountCrashFunction count_crash_function_;
   std::string our_path_;
   bool initialized_;
   IsFeedbackAllowedFunction is_feedback_allowed_function_;
   SystemLogging *logger_;
+
+  static const char *kUserId;
+  static const char *kGroupId;
 };
 
-#endif  // _CRASH_USER_COLLECTOR_H_
+#endif  // _CRASH_REPORTER_USER_COLLECTOR_H_
diff --git a/crash_reporter/user_collector_test.cc b/crash_reporter/user_collector_test.cc
index 71cce62..335821c 100644
--- a/crash_reporter/user_collector_test.cc
+++ b/crash_reporter/user_collector_test.cc
@@ -2,12 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include <gflags/gflags.h>
-#include <gtest/gtest.h>
+#include <unistd.h>
 
 #include "base/file_util.h"
 #include "crash-reporter/system_logging_mock.h"
 #include "crash-reporter/user_collector.h"
+#include "gflags/gflags.h"
+#include "gtest/gtest.h"
 
 int s_crashes = 0;
 bool s_metrics = false;
@@ -28,13 +29,18 @@
     collector_.Initialize(CountCrash,
                           kFilePath,
                           IsMetrics,
-                          &logging_);
+                          &logging_,
+                          false);
     mkdir("test", 0777);
     collector_.set_core_pattern_file("test/core_pattern");
+    pid_ = getpid();
   }
  protected:
+  void TestEnableOK(bool generate_diagnostics);
+
   SystemLoggingMock logging_;
   UserCollector collector_;
+  pid_t pid_;
 };
 
 TEST_F(UserCollectorTest, EnableOK) {
@@ -42,8 +48,7 @@
   ASSERT_TRUE(collector_.Enable());
   ASSERT_TRUE(file_util::ReadFileToString(FilePath("test/core_pattern"),
                                                    &contents));
-  ASSERT_STREQ(contents.c_str(),
-               "|/my/path --signal=%s --pid=%p --exec=%e");
+  ASSERT_EQ("|/my/path --signal=%s --pid=%p", contents);
   ASSERT_EQ(s_crashes, 0);
   ASSERT_NE(logging_.log().find("Enabling crash handling"), std::string::npos);
 }
@@ -62,7 +67,7 @@
   ASSERT_TRUE(collector_.Disable());
   ASSERT_TRUE(file_util::ReadFileToString(FilePath("test/core_pattern"),
                                           &contents));
-  ASSERT_STREQ(contents.c_str(), "core");
+  ASSERT_EQ("core", contents);
   ASSERT_EQ(s_crashes, 0);
   ASSERT_NE(logging_.log().find("Disabling crash handling"),
             std::string::npos);
@@ -77,7 +82,6 @@
             std::string::npos);
 }
 
-
 TEST_F(UserCollectorTest, HandleCrashWithoutMetrics) {
   s_metrics = false;
   collector_.HandleCrash(10, 20, "foobar");
@@ -96,6 +100,215 @@
   ASSERT_EQ(s_crashes, 1);
 }
 
+TEST_F(UserCollectorTest, GetProcessPath) {
+  FilePath path = collector_.GetProcessPath(100);
+  ASSERT_EQ("/proc/100", path.value());
+}
+
+TEST_F(UserCollectorTest, GetSymlinkTarget) {
+  FilePath result;
+  ASSERT_FALSE(collector_.GetSymlinkTarget(FilePath("/does_not_exist"),
+                                           &result));
+
+  std::string long_link;
+  for (int i = 0; i < 50; ++i)
+    long_link += "0123456789";
+  long_link += "/gold";
+
+  for (size_t len = 1; len <= long_link.size(); ++len) {
+    std::string this_link;
+    static const char kLink[] = "test/this_link";
+    this_link.assign(long_link.c_str(), len);
+    ASSERT_EQ(len, this_link.size());
+    unlink(kLink);
+    ASSERT_EQ(0, symlink(this_link.c_str(), kLink));
+    ASSERT_TRUE(collector_.GetSymlinkTarget(FilePath(kLink), &result));
+    ASSERT_EQ(this_link, result.value());
+  }
+}
+
+TEST_F(UserCollectorTest, GetIdFromStatus) {
+  int id = 1;
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                          UserCollector::kIdEffective,
+                                          "nothing here",
+                                          &id));
+  EXPECT_EQ(id, 1);
+
+  // Not enough parameters.
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                          UserCollector::kIdReal,
+                                          "line 1\nUid:\t1\n", &id));
+
+  const char valid_contents[] = "\nUid:\t1\t2\t3\t4\nGid:\t5\t6\t7\t8\n";
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                         UserCollector::kIdReal,
+                                         valid_contents,
+                                         &id));
+  EXPECT_EQ(1, id);
+
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                         UserCollector::kIdEffective,
+                                         valid_contents,
+                                         &id));
+  EXPECT_EQ(2, id);
+
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                         UserCollector::kIdFileSystem,
+                                         valid_contents,
+                                         &id));
+  EXPECT_EQ(4, id);
+
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kGroupId,
+                                         UserCollector::kIdEffective,
+                                         valid_contents,
+                                         &id));
+  EXPECT_EQ(6, id);
+
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kGroupId,
+                                         UserCollector::kIdSet,
+                                         valid_contents,
+                                         &id));
+  EXPECT_EQ(7, id);
+
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kGroupId,
+                                          UserCollector::IdKind(5),
+                                          valid_contents,
+                                          &id));
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kGroupId,
+                                          UserCollector::IdKind(-1),
+                                          valid_contents,
+                                          &id));
+
+  // Fail if junk after number
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                          UserCollector::kIdReal,
+                                          "Uid:\t1f\t2\t3\t4\n",
+                                          &id));
+  EXPECT_TRUE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                         UserCollector::kIdReal,
+                                         "Uid:\t1\t2\t3\t4\n",
+                                         &id));
+  EXPECT_EQ(1, id);
+
+  // Fail if more than 4 numbers.
+  EXPECT_FALSE(collector_.GetIdFromStatus(UserCollector::kUserId,
+                                          UserCollector::kIdReal,
+                                          "Uid:\t1\t2\t3\t4\t5\n",
+                                          &id));
+}
+
+TEST_F(UserCollectorTest, GetUserInfoFromName) {
+  gid_t gid = 100;
+  uid_t uid = 100;
+  EXPECT_TRUE(collector_.GetUserInfoFromName("root", &uid, &gid));
+  EXPECT_EQ(0, uid);
+  EXPECT_EQ(0, gid);
+}
+
+TEST_F(UserCollectorTest, GetCrashDirectoryInfo) {
+  FilePath path;
+  const int kRootUid = 0;
+  const int kRootGid = 0;
+  const int kNtpUid = 5;
+  const int kChronosUid = 1000;
+  const int kChronosGid = 1001;
+  const mode_t kExpectedSystemMode = 01755;
+  const mode_t kExpectedUserMode = 0755;
+
+  mode_t directory_mode;
+  uid_t directory_owner;
+  gid_t directory_group;
+
+  path = collector_.GetCrashDirectoryInfo(kRootUid,
+                                          kChronosUid,
+                                          kChronosGid,
+                                          &directory_mode,
+                                          &directory_owner,
+                                          &directory_group);
+  EXPECT_EQ("/var/spool/crash", path.value());
+  EXPECT_EQ(kExpectedSystemMode, directory_mode);
+  EXPECT_EQ(kRootUid, directory_owner);
+  EXPECT_EQ(kRootGid, directory_group);
+
+  path = collector_.GetCrashDirectoryInfo(kNtpUid,
+                                          kChronosUid,
+                                          kChronosGid,
+                                          &directory_mode,
+                                          &directory_owner,
+                                          &directory_group);
+  EXPECT_EQ("/var/spool/crash", path.value());
+  EXPECT_EQ(kExpectedSystemMode, directory_mode);
+  EXPECT_EQ(kRootUid, directory_owner);
+  EXPECT_EQ(kRootGid, directory_group);
+
+  path = collector_.GetCrashDirectoryInfo(kChronosUid,
+                                          kChronosUid,
+                                          kChronosGid,
+                                          &directory_mode,
+                                          &directory_owner,
+                                          &directory_group);
+  EXPECT_EQ("/home/chronos/user/crash", path.value());
+  EXPECT_EQ(kExpectedUserMode, directory_mode);
+  EXPECT_EQ(kChronosUid, directory_owner);
+  EXPECT_EQ(kChronosGid, directory_group);
+}
+
+TEST_F(UserCollectorTest, CopyOffProcFilesBadPath) {
+  // Try a path that is not writable.
+  ASSERT_FALSE(collector_.CopyOffProcFiles(pid_, FilePath("/bad/path")));
+  ASSERT_NE(logging_.log().find(
+      "Could not create /bad/path"),
+            std::string::npos);
+}
+
+TEST_F(UserCollectorTest, CopyOffProcFilesBadPid) {
+  FilePath container_path("test/container");
+  ASSERT_FALSE(collector_.CopyOffProcFiles(0, container_path));
+  ASSERT_NE(logging_.log().find(
+      "Path /proc/0 does not exist"),
+            std::string::npos);
+}
+
+TEST_F(UserCollectorTest, CopyOffProcFilesOK) {
+  FilePath container_path("test/container");
+  ASSERT_TRUE(collector_.CopyOffProcFiles(pid_, container_path));
+  ASSERT_EQ(logging_.log().find(
+      "Could not copy"), std::string::npos);
+  static struct {
+    const char *name;
+    bool exists;
+  } expectations[] = {
+    { "auxv", true },
+    { "cmdline", true },
+    { "environ", true },
+    { "maps", true },
+    { "mem", false },
+    { "mounts", false },
+    { "sched", false },
+    { "status", true }
+  };
+  for (unsigned i = 0; i < sizeof(expectations)/sizeof(expectations[0]); ++i) {
+    EXPECT_EQ(expectations[i].exists,
+              file_util::PathExists(
+                  container_path.Append(expectations[i].name)));
+  }
+}
+
+TEST_F(UserCollectorTest, FormatDumpBasename) {
+  struct tm tm = {0};
+  tm.tm_sec = 15;
+  tm.tm_min = 50;
+  tm.tm_hour = 13;
+  tm.tm_mday = 23;
+  tm.tm_mon = 4;
+  tm.tm_year = 110;
+  tm.tm_isdst = -1;
+  std::string basename =
+      collector_.FormatDumpBasename("foo", mktime(&tm), 100);
+  ASSERT_EQ("foo.20100523.135015.100", basename);
+}
+
 int main(int argc, char **argv) {
   ::testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();