Merge "Fix bug in writing zips."
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 6817234..fd61bda 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -134,9 +134,7 @@
   // - Recursive, so it uses stack space relative to number of directory
   //   components.
 
-  const std::string parent(adb_dirname(path));
-
-  if (directory_exists(parent)) {
+  if (directory_exists(path)) {
     return true;
   }
 
@@ -144,19 +142,21 @@
   // This can happen on Windows when walking up the directory hierarchy and not
   // finding anything that already exists (unlike POSIX that will eventually
   // find . or /).
+  const std::string parent(adb_dirname(path));
+
   if (parent == path) {
     errno = ENOENT;
     return false;
   }
 
-  // Recursively make parent directories of 'parent'.
+  // Recursively make parent directories of 'path'.
   if (!mkdirs(parent)) {
     return false;
   }
 
-  // Now that the parent directory hierarchy of 'parent' has been ensured,
+  // Now that the parent directory hierarchy of 'path' has been ensured,
   // create parent itself.
-  if (adb_mkdir(parent, 0775) == -1) {
+  if (adb_mkdir(path, 0775) == -1) {
     // Can't just check for errno == EEXIST because it might be a file that
     // exists.
     const int saved_errno = errno;
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index c5eabcf..785fef3 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -1074,7 +1074,6 @@
     if (argc < 2) return usage();
 
     adb_unlink(filename);
-    mkdirs(filename);
     int outFd = adb_creat(filename, 0640);
     if (outFd < 0) {
         fprintf(stderr, "adb: unable to open file %s\n", filename);
diff --git a/adb/file_sync_client.cpp b/adb/file_sync_client.cpp
index 6087c06..d2bc3cd 100644
--- a/adb/file_sync_client.cpp
+++ b/adb/file_sync_client.cpp
@@ -392,7 +392,12 @@
     if (!sc.SendRequest(ID_RECV, rpath)) return false;
 
     adb_unlink(lpath);
-    mkdirs(lpath);
+    if (!mkdirs(adb_dirname(lpath))) {
+        sc.Error("failed to create parent directory '%s': %s",
+                 adb_dirname(lpath).c_str(), strerror(errno));
+        return false;
+    }
+
     int lfd = adb_creat(lpath, 0644);
     if (lfd < 0) {
         sc.Error("cannot create '%s': %s", lpath, strerror(errno));
diff --git a/adb/file_sync_service.cpp b/adb/file_sync_service.cpp
index 298ed82..7484a7c 100644
--- a/adb/file_sync_service.cpp
+++ b/adb/file_sync_service.cpp
@@ -32,6 +32,7 @@
 
 #include "adb.h"
 #include "adb_io.h"
+#include "adb_utils.h"
 #include "private/android_filesystem_config.h"
 
 #include <base/stringprintf.h>
@@ -53,8 +54,6 @@
     if (path[0] != '/') return false;
 
     std::vector<std::string> path_components = android::base::Split(path, "/");
-    path_components.pop_back(); // For "/system/bin/sh", only create "/system/bin".
-
     std::string partial_path;
     for (const auto& path_component : path_components) {
         if (partial_path.back() != OS_PATH_SEPARATOR) partial_path += OS_PATH_SEPARATOR;
@@ -149,7 +148,7 @@
 
     int fd = adb_open_mode(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode);
     if (fd < 0 && errno == ENOENT) {
-        if (!secure_mkdirs(path)) {
+        if (!secure_mkdirs(adb_dirname(path))) {
             SendSyncFailErrno(s, "secure_mkdirs failed");
             goto fail;
         }
@@ -244,7 +243,7 @@
 
     ret = symlink(&buffer[0], path.c_str());
     if (ret && errno == ENOENT) {
-        if (!secure_mkdirs(path)) {
+        if (!secure_mkdirs(adb_dirname(path))) {
             SendSyncFailErrno(s, "secure_mkdirs failed");
             return false;
         }
diff --git a/crash_reporter/Android.mk b/crash_reporter/Android.mk
index c5ca4e4..81cb458 100644
--- a/crash_reporter/Android.mk
+++ b/crash_reporter/Android.mk
@@ -102,9 +102,13 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)
 include $(BUILD_SYSTEM)/base_rules.mk
 
+# Optionally populate the BRILLO_CRASH_SERVER variable from a product
+# configuration file: brillo/crash_server.
+LOADED_BRILLO_CRASH_SERVER := $(call cfgtree-get-if-exists,brillo/crash_server)
+
 # If the crash server isn't set, use a blank value.  crash_sender
 # will log it as a configuration error.
-$(LOCAL_BUILT_MODULE): BRILLO_CRASH_SERVER ?= ""
+$(LOCAL_BUILT_MODULE): BRILLO_CRASH_SERVER ?= "$(LOADED_BRILLO_CRASH_SERVER)"
 $(LOCAL_BUILT_MODULE):
 	$(hide)mkdir -p $(dir $@)
 	echo $(BRILLO_CRASH_SERVER) > $@
diff --git a/gatekeeperd/SoftGateKeeper.h b/gatekeeperd/SoftGateKeeper.h
index 75fe11d..c8010ca 100644
--- a/gatekeeperd/SoftGateKeeper.h
+++ b/gatekeeperd/SoftGateKeeper.h
@@ -25,8 +25,10 @@
 #include <crypto_scrypt.h>
 }
 
+#include <base/memory.h>
 #include <UniquePtr.h>
 #include <gatekeeper/gatekeeper.h>
+
 #include <iostream>
 #include <unordered_map>
 
@@ -150,14 +152,15 @@
     }
 
     bool DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
-        FastHashMap::const_iterator it = fast_hash_map_.find(expected_handle->user_id);
+        uint64_t user_id = android::base::get_unaligned(&expected_handle->user_id);
+        FastHashMap::const_iterator it = fast_hash_map_.find(user_id);
         if (it != fast_hash_map_.end() && VerifyFast(it->second, password)) {
             return true;
         } else {
             if (GateKeeper::DoVerify(expected_handle, password)) {
                 uint64_t salt;
                 GetRandom(&salt, sizeof(salt));
-                fast_hash_map_[expected_handle->user_id] = ComputeFastHash(password, salt);
+                fast_hash_map_[user_id] = ComputeFastHash(password, salt);
                 return true;
             }
         }
diff --git a/gatekeeperd/tests/Android.mk b/gatekeeperd/tests/Android.mk
index 6fc4ac0..a62b1d4 100644
--- a/gatekeeperd/tests/Android.mk
+++ b/gatekeeperd/tests/Android.mk
@@ -20,7 +20,7 @@
 LOCAL_MODULE := gatekeeperd-unit-tests
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CFLAGS += -g -Wall -Werror -std=gnu++11 -Wno-missing-field-initializers
-LOCAL_SHARED_LIBRARIES := libgatekeeper libcrypto
+LOCAL_SHARED_LIBRARIES := libgatekeeper libcrypto libbase
 LOCAL_STATIC_LIBRARIES := libscrypt_static
 LOCAL_C_INCLUDES := external/scrypt/lib/crypto
 LOCAL_SRC_FILES := \
diff --git a/include/utils/LruCache.h b/include/utils/LruCache.h
index 20a379e..1741fb2 100644
--- a/include/utils/LruCache.h
+++ b/include/utils/LruCache.h
@@ -17,10 +17,9 @@
 #ifndef ANDROID_UTILS_LRU_CACHE_H
 #define ANDROID_UTILS_LRU_CACHE_H
 
+#include <memory>
 #include <unordered_set>
 
-#include <UniquePtr.h>
-
 #include "utils/TypeHelpers.h"  // hash_t
 
 namespace android {
@@ -91,7 +90,7 @@
         return result;
     }
 
-    UniquePtr<LruCacheSet> mSet;
+    std::unique_ptr<LruCacheSet> mSet;
     OnEntryRemoved<TKey, TValue>* mListener;
     Entry* mOldest;
     Entry* mYoungest;
diff --git a/libutils/CallStack.cpp b/libutils/CallStack.cpp
index 0bfb520..699da74 100644
--- a/libutils/CallStack.cpp
+++ b/libutils/CallStack.cpp
@@ -16,11 +16,12 @@
 
 #define LOG_TAG "CallStack"
 
+#include <memory>
+
 #include <utils/CallStack.h>
 #include <utils/Printer.h>
 #include <utils/Errors.h>
 #include <utils/Log.h>
-#include <UniquePtr.h>
 
 #include <backtrace/Backtrace.h>
 
@@ -40,7 +41,7 @@
 void CallStack::update(int32_t ignoreDepth, pid_t tid) {
     mFrameLines.clear();
 
-    UniquePtr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
+    std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
     if (!backtrace->Unwind(ignoreDepth)) {
         ALOGW("%s: Failed to unwind callstack.", __FUNCTION__);
     }
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
index b08c153..291c983 100644
--- a/metricsd/Android.mk
+++ b/metricsd/Android.mk
@@ -27,6 +27,7 @@
 
 metrics_daemon_common := \
   collectors/averaged_statistics_collector.cc \
+  collectors/cpu_usage_collector.cc \
   collectors/disk_usage_collector.cc \
   metrics_daemon.cc \
   persistent_integer.cc \
@@ -41,6 +42,7 @@
 
 metrics_tests_sources := \
   collectors/averaged_statistics_collector_test.cc \
+  collectors/cpu_usage_collector_test.cc \
   metrics_daemon_test.cc \
   metrics_library_test.cc \
   persistent_integer_test.cc \
diff --git a/metricsd/collectors/cpu_usage_collector.cc b/metricsd/collectors/cpu_usage_collector.cc
new file mode 100644
index 0000000..05934b4
--- /dev/null
+++ b/metricsd/collectors/cpu_usage_collector.cc
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "collectors/cpu_usage_collector.h"
+
+#include <base/bind.h>
+#include <base/files/file_path.h>
+#include <base/files/file_util.h>
+#include <base/message_loop/message_loop.h>
+#include <base/strings/string_number_conversions.h>
+#include <base/strings/string_split.h>
+#include <base/strings/string_util.h>
+#include <base/sys_info.h>
+
+#include "metrics/metrics_library.h"
+
+namespace {
+
+const char kCpuUsagePercent[] = "Platform.CpuUsage.Percent";
+const char kMetricsProcStatFileName[] = "/proc/stat";
+const int kMetricsProcStatFirstLineItemsCount = 11;
+
+// Collect every minute.
+const int kCollectionIntervalSecs = 60;
+
+}  // namespace
+
+using base::TimeDelta;
+
+CpuUsageCollector::CpuUsageCollector(MetricsLibraryInterface* metrics_library) {
+  CHECK(metrics_library);
+  metrics_lib_ = metrics_library;
+  collect_interval_ = TimeDelta::FromSeconds(kCollectionIntervalSecs);
+}
+
+void CpuUsageCollector::Init() {
+  num_cpu_ = base::SysInfo::NumberOfProcessors();
+
+  // Get ticks per second (HZ) on this system.
+  // Sysconf cannot fail, so no sanity checks are needed.
+  ticks_per_second_ = sysconf(_SC_CLK_TCK);
+  CHECK_GT(ticks_per_second_, uint64_t(0))
+      << "Number of ticks per seconds should be positive.";
+
+  latest_cpu_use_ = GetCumulativeCpuUse();
+}
+
+void CpuUsageCollector::CollectCallback() {
+  Collect();
+  Schedule();
+}
+
+void CpuUsageCollector::Schedule() {
+  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
+      base::Bind(&CpuUsageCollector::CollectCallback, base::Unretained(this)),
+      collect_interval_);
+}
+
+void CpuUsageCollector::Collect() {
+  TimeDelta cpu_use = GetCumulativeCpuUse();
+  TimeDelta diff_per_cpu = (cpu_use - latest_cpu_use_) / num_cpu_;
+  latest_cpu_use_ = cpu_use;
+
+  // Report the cpu usage as a percentage of the total cpu usage possible.
+  int percent_use = diff_per_cpu.InMilliseconds() * 100 /
+      (kCollectionIntervalSecs * 1000);
+
+  metrics_lib_->SendEnumToUMA(kCpuUsagePercent, percent_use, 101);
+}
+
+TimeDelta CpuUsageCollector::GetCumulativeCpuUse() {
+  base::FilePath proc_stat_path(kMetricsProcStatFileName);
+  std::string proc_stat_string;
+  if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
+    LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
+    return TimeDelta();
+  }
+
+  uint64_t user_ticks, user_nice_ticks, system_ticks;
+  if (!ParseProcStat(proc_stat_string, &user_ticks, &user_nice_ticks,
+                     &system_ticks)) {
+    return TimeDelta();
+  }
+
+  uint64_t total = user_ticks + user_nice_ticks + system_ticks;
+  return TimeDelta::FromMicroseconds(
+      total * 1000 * 1000 / ticks_per_second_);
+}
+
+bool CpuUsageCollector::ParseProcStat(const std::string& stat_content,
+                                      uint64_t *user_ticks,
+                                      uint64_t *user_nice_ticks,
+                                      uint64_t *system_ticks) {
+  std::vector<std::string> proc_stat_lines;
+  base::SplitString(stat_content, '\n', &proc_stat_lines);
+  if (proc_stat_lines.empty()) {
+    LOG(WARNING) << "No lines found in " << kMetricsProcStatFileName;
+    return false;
+  }
+  std::vector<std::string> proc_stat_totals;
+  base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
+
+  if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
+      proc_stat_totals[0] != "cpu" ||
+      !base::StringToUint64(proc_stat_totals[1], user_ticks) ||
+      !base::StringToUint64(proc_stat_totals[2], user_nice_ticks) ||
+      !base::StringToUint64(proc_stat_totals[3], system_ticks)) {
+    LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
+    return false;
+  }
+  return true;
+}
diff --git a/metricsd/collectors/cpu_usage_collector.h b/metricsd/collectors/cpu_usage_collector.h
new file mode 100644
index 0000000..f81dfcb
--- /dev/null
+++ b/metricsd/collectors/cpu_usage_collector.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
+#define METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
+
+#include <base/time/time.h>
+
+#include "metrics/metrics_library.h"
+
+class CpuUsageCollector {
+ public:
+  CpuUsageCollector(MetricsLibraryInterface* metrics_library);
+
+  // Initialize this collector's state.
+  void Init();
+
+  // Schedule a collection interval.
+  void Schedule();
+
+  // Callback called at the end of the collection interval.
+  void CollectCallback();
+
+  // Measure the cpu use and report it.
+  void Collect();
+
+  // Gets the current cumulated Cpu usage.
+  base::TimeDelta GetCumulativeCpuUse();
+
+ private:
+  FRIEND_TEST(CpuUsageTest, ParseProcStat);
+  bool ParseProcStat(const std::string& stat_content,
+                     uint64_t *user_ticks,
+                     uint64_t *user_nice_ticks,
+                     uint64_t *system_ticks);
+
+  int num_cpu_;
+  uint32_t ticks_per_second_;
+
+  base::TimeDelta collect_interval_;
+  base::TimeDelta latest_cpu_use_;
+
+  MetricsLibraryInterface* metrics_lib_;
+};
+
+#endif  // METRICSD_COLLECTORS_CPU_USAGE_COLLECTOR_H_
diff --git a/metricsd/collectors/cpu_usage_collector_test.cc b/metricsd/collectors/cpu_usage_collector_test.cc
new file mode 100644
index 0000000..ee5c92b
--- /dev/null
+++ b/metricsd/collectors/cpu_usage_collector_test.cc
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include "collectors/cpu_usage_collector.h"
+#include "metrics/metrics_library_mock.h"
+
+
+TEST(CpuUsageTest, ParseProcStat) {
+  MetricsLibraryMock metrics_lib_mock;
+  CpuUsageCollector collector(&metrics_lib_mock);
+  std::vector<std::string> invalid_contents = {
+    "",
+    // First line does not start with cpu.
+    "spu  17191 11 36579 151118 289 0 2 0 0 0\n"
+    "cpu0 1564 2 866 48650 68 0 2 0 0 0\n"
+    "cpu1 14299 0 35116 1844 81 0 0 0 0 0\n",
+    // One of the field is not a number.
+    "cpu  a17191 11 36579 151118 289 0 2 0 0 0",
+    // To many numbers in the first line.
+    "cpu  17191 11 36579 151118 289 0 2 0 0 0 102"
+  };
+
+  uint64_t user, nice, system;
+  for (int i = 0; i < invalid_contents.size(); i++) {
+    ASSERT_FALSE(collector.ParseProcStat(invalid_contents[i], &user, &nice,
+                                         &system));
+  }
+
+  ASSERT_TRUE(collector.ParseProcStat(
+      std::string("cpu  17191 11 36579 151118 289 0 2 0 0 0"),
+      &user, &nice, &system));
+  ASSERT_EQ(17191, user);
+  ASSERT_EQ(11, nice);
+  ASSERT_EQ(36579, system);
+}
diff --git a/metricsd/metrics_daemon.cc b/metricsd/metrics_daemon.cc
index ed786e1..b606fd0 100644
--- a/metricsd/metrics_daemon.cc
+++ b/metricsd/metrics_daemon.cc
@@ -71,10 +71,8 @@
 
 const int kMetricMeminfoInterval = 30;    // seconds
 
-const char kMetricsProcStatFileName[] = "/proc/stat";
 const char kMeminfoFileName[] = "/proc/meminfo";
 const char kVmStatFileName[] = "/proc/vmstat";
-const int kMetricsProcStatFirstLineItemsCount = 11;
 
 // Thermal CPU throttling.
 
@@ -103,9 +101,7 @@
 
 MetricsDaemon::MetricsDaemon()
     : memuse_final_time_(0),
-      memuse_interval_index_(0),
-      ticks_per_second_(0),
-      latest_cpu_use_ticks_(0) {}
+      memuse_interval_index_(0) {}
 
 MetricsDaemon::~MetricsDaemon() {
 }
@@ -188,10 +184,6 @@
   upload_interval_ = upload_interval;
   server_ = server;
 
-  // Get ticks per second (HZ) on this system.
-  // Sysconf cannot fail, so no sanity checks are needed.
-  ticks_per_second_ = sysconf(_SC_CLK_TCK);
-
   daily_active_use_.reset(
       new PersistentInteger("Platform.UseTime.PerDay"));
   version_cumulative_active_use_.reset(
@@ -235,6 +227,7 @@
   averaged_stats_collector_.reset(
       new AveragedStatisticsCollector(metrics_lib_, diskstats_path,
                                       kVmStatFileName));
+  cpu_usage_collector_.reset(new CpuUsageCollector(metrics_lib_));
 }
 
 int MetricsDaemon::OnInit() {
@@ -290,6 +283,7 @@
         base::Bind(&MetricsDaemon::OnDisableMetrics, base::Unretained(this)));
   }
 
+  latest_cpu_use_microseconds_ = cpu_usage_collector_->GetCumulativeCpuUse();
   base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
       base::Bind(&MetricsDaemon::HandleUpdateStatsTimeout,
                  base::Unretained(this)),
@@ -404,53 +398,6 @@
   return DBUS_HANDLER_RESULT_HANDLED;
 }
 
-// One might argue that parts of this should go into
-// chromium/src/base/sys_info_chromeos.c instead, but put it here for now.
-
-TimeDelta MetricsDaemon::GetIncrementalCpuUse() {
-  FilePath proc_stat_path = FilePath(kMetricsProcStatFileName);
-  std::string proc_stat_string;
-  if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
-    LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
-    return TimeDelta();
-  }
-
-  std::vector<std::string> proc_stat_lines;
-  base::SplitString(proc_stat_string, '\n', &proc_stat_lines);
-  if (proc_stat_lines.empty()) {
-    LOG(WARNING) << "cannot parse " << kMetricsProcStatFileName
-                 << ": " << proc_stat_string;
-    return TimeDelta();
-  }
-  std::vector<std::string> proc_stat_totals;
-  base::SplitStringAlongWhitespace(proc_stat_lines[0], &proc_stat_totals);
-
-  uint64_t user_ticks, user_nice_ticks, system_ticks;
-  if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
-      proc_stat_totals[0] != "cpu" ||
-      !base::StringToUint64(proc_stat_totals[1], &user_ticks) ||
-      !base::StringToUint64(proc_stat_totals[2], &user_nice_ticks) ||
-      !base::StringToUint64(proc_stat_totals[3], &system_ticks)) {
-    LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
-    return TimeDelta(base::TimeDelta::FromSeconds(0));
-  }
-
-  uint64_t total_cpu_use_ticks = user_ticks + user_nice_ticks + system_ticks;
-
-  // Sanity check.
-  if (total_cpu_use_ticks < latest_cpu_use_ticks_) {
-    LOG(WARNING) << "CPU time decreasing from " << latest_cpu_use_ticks_
-                 << " to " << total_cpu_use_ticks;
-    return TimeDelta();
-  }
-
-  uint64_t diff = total_cpu_use_ticks - latest_cpu_use_ticks_;
-  latest_cpu_use_ticks_ = total_cpu_use_ticks;
-  // Use microseconds to avoid significant truncations.
-  return base::TimeDelta::FromMicroseconds(
-      diff * 1000 * 1000 / ticks_per_second_);
-}
-
 void MetricsDaemon::ProcessUserCrash() {
   // Counts the active time up to now.
   UpdateStats(TimeTicks::Now(), Time::Now());
@@ -506,6 +453,9 @@
 void MetricsDaemon::StatsReporterInit() {
   disk_usage_collector_->Schedule();
 
+  cpu_usage_collector_->Init();
+  cpu_usage_collector_->Schedule();
+
   // Don't start a collection cycle during the first run to avoid delaying the
   // boot.
   averaged_stats_collector_->ScheduleWait();
@@ -910,7 +860,10 @@
   version_cumulative_active_use_->Add(elapsed_seconds);
   user_crash_interval_->Add(elapsed_seconds);
   kernel_crash_interval_->Add(elapsed_seconds);
-  version_cumulative_cpu_use_->Add(GetIncrementalCpuUse().InMilliseconds());
+  TimeDelta cpu_use = cpu_usage_collector_->GetCumulativeCpuUse();
+  version_cumulative_cpu_use_->Add(
+      (cpu_use - latest_cpu_use_microseconds_).InMilliseconds());
+  latest_cpu_use_microseconds_ = cpu_use;
   last_update_stats_time_ = now_ticks;
 
   const TimeDelta since_epoch = now_wall_time - Time::UnixEpoch();
diff --git a/metricsd/metrics_daemon.h b/metricsd/metrics_daemon.h
index 3d691c5..f12b02e 100644
--- a/metricsd/metrics_daemon.h
+++ b/metricsd/metrics_daemon.h
@@ -32,6 +32,7 @@
 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
 
 #include "collectors/averaged_statistics_collector.h"
+#include "collectors/cpu_usage_collector.h"
 #include "collectors/disk_usage_collector.h"
 #include "metrics/metrics_library.h"
 #include "persistent_integer.h"
@@ -164,10 +165,6 @@
   // total number of kernel crashes since the last version update.
   void SendKernelCrashesCumulativeCountStats();
 
-  // Returns the total (system-wide) CPU usage between the time of the most
-  // recent call to this function and now.
-  base::TimeDelta GetIncrementalCpuUse();
-
   // Sends a sample representing the number of seconds of active use
   // for a 24-hour period and reset |use|.
   void SendAndResetDailyUseSample(
@@ -268,12 +265,9 @@
   // Selects the wait time for the next memory use callback.
   unsigned int memuse_interval_index_;
 
-  // The system "HZ", or frequency of ticks.  Some system data uses ticks as a
-  // unit, and this is used to convert to standard time units.
-  uint32_t ticks_per_second_;
   // Used internally by GetIncrementalCpuUse() to return the CPU utilization
   // between calls.
-  uint64_t latest_cpu_use_ticks_;
+  base::TimeDelta latest_cpu_use_microseconds_;
 
   // Persistent values and accumulators for crash statistics.
   scoped_ptr<PersistentInteger> daily_cycle_;
@@ -302,6 +296,8 @@
   scoped_ptr<PersistentInteger> kernel_crashes_version_count_;
   scoped_ptr<PersistentInteger> unclean_shutdowns_daily_count_;
   scoped_ptr<PersistentInteger> unclean_shutdowns_weekly_count_;
+
+  scoped_ptr<CpuUsageCollector> cpu_usage_collector_;
   scoped_ptr<DiskUsageCollector> disk_usage_collector_;
   scoped_ptr<AveragedStatisticsCollector> averaged_stats_collector_;
 
diff --git a/packagelistparser/Android.mk b/packagelistparser/Android.mk
index 802a3cb..c8be050 100644
--- a/packagelistparser/Android.mk
+++ b/packagelistparser/Android.mk
@@ -6,9 +6,9 @@
 LOCAL_MODULE := libpackagelistparser
 LOCAL_MODULE_TAGS := optional
 LOCAL_SRC_FILES := packagelistparser.c
-LOCAL_COPY_HEADERS_TO := packagelistparser
-LOCAL_COPY_HEADERS := packagelistparser.h
 LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 
 LOCAL_CLANG := true
 LOCAL_SANITIZE := integer
@@ -22,9 +22,9 @@
 LOCAL_MODULE := libpackagelistparser
 LOCAL_MODULE_TAGS := optional
 LOCAL_SRC_FILES := packagelistparser.c
-LOCAL_COPY_HEADERS_TO := packagelistparser
-LOCAL_COPY_HEADERS := packagelistparser.h
 LOCAL_STATIC_LIBRARIES := liblog
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 
 LOCAL_CLANG := true
 LOCAL_SANITIZE := integer
diff --git a/packagelistparser/packagelistparser.h b/packagelistparser/include/packagelistparser/packagelistparser.h
similarity index 100%
rename from packagelistparser/packagelistparser.h
rename to packagelistparser/include/packagelistparser/packagelistparser.h
diff --git a/packagelistparser/packagelistparser.c b/packagelistparser/packagelistparser.c
index 3e2539c..16052e2 100644
--- a/packagelistparser/packagelistparser.c
+++ b/packagelistparser/packagelistparser.c
@@ -29,7 +29,7 @@
 #define LOG_TAG "packagelistparser"
 #include <utils/Log.h>
 
-#include "packagelistparser.h"
+#include <packagelistparser/packagelistparser.h>
 
 #define CLOGE(fmt, ...) \
     do {\