Merge "init: improve mmap ASLR failure reporting"
diff --git a/base/include/android-base/thread_annotations.h b/base/include/android-base/thread_annotations.h
new file mode 100644
index 0000000..90979df
--- /dev/null
+++ b/base/include/android-base/thread_annotations.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2016 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 UTILS_THREAD_ANNOTATIONS_H
+#define UTILS_THREAD_ANNOTATIONS_H
+
+#if defined(__SUPPORT_TS_ANNOTATION__) || defined(__clang__)
+#define THREAD_ANNOTATION_ATTRIBUTE__(x)   __attribute__((x))
+#else
+#define THREAD_ANNOTATION_ATTRIBUTE__(x)   // no-op
+#endif
+
+#define CAPABILITY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
+
+#define SCOPED_CAPABILITY \
+      THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
+
+#define GUARDED_BY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
+
+#define PT_GUARDED_BY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
+
+#define ACQUIRED_BEFORE(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
+
+#define ACQUIRED_AFTER(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
+
+#define REQUIRES(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
+
+#define REQUIRES_SHARED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
+
+#define ACQUIRE(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
+
+#define ACQUIRE_SHARED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
+
+#define RELEASE(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
+
+#define RELEASE_SHARED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
+
+#define TRY_ACQUIRE(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
+
+#define TRY_ACQUIRE_SHARED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
+
+#define EXCLUDES(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
+
+#define ASSERT_CAPABILITY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
+
+#define ASSERT_SHARED_CAPABILITY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
+
+#define RETURN_CAPABILITY(x) \
+      THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
+
+#define NO_THREAD_SAFETY_ANALYSIS \
+      THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
+
+#endif  // UTILS_THREAD_ANNOTATIONS_H
diff --git a/bootstat/Android.mk b/bootstat/Android.mk
index 3d02752..6300941 100644
--- a/bootstat/Android.mk
+++ b/bootstat/Android.mk
@@ -21,6 +21,7 @@
 bootstat_lib_src_files := \
         boot_event_record_store.cpp \
         event_log_list_builder.cpp \
+        histogram_logger.cpp \
         uptime_parser.cpp \
 
 bootstat_src_files := \
@@ -41,17 +42,13 @@
         -Wextra \
         -Werror \
 
-bootstat_cppflags := \
-        -Wno-non-virtual-dtor \
-
-bootstat_debug_cflags := \
-        $(bootstat_cflags) \
-        -UNDEBUG \
-
 # 524291 corresponds to sysui_histogram, from
 # frameworks/base/core/java/com/android/internal/logging/EventLogTags.logtags
 bootstat_cflags += -DHISTOGRAM_LOG_TAG=524291
 
+bootstat_debug_cflags := \
+        $(bootstat_cflags) \
+        -UNDEBUG \
 
 # bootstat static library
 # -----------------------------------------------------------------------------
@@ -60,7 +57,6 @@
 
 LOCAL_MODULE := libbootstat
 LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_CPPFLAGS := $(bootstat_cppflags)
 LOCAL_C_INCLUDES := $(bootstat_c_includes)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_SRC_FILES := $(bootstat_lib_src_files)
@@ -76,7 +72,6 @@
 
 LOCAL_MODULE := libbootstat_debug
 LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_CPPFLAGS := $(bootstat_debug_cppflags)
 LOCAL_C_INCLUDES := $(bootstat_c_includes)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_SRC_FILES := $(bootstat_lib_src_files)
@@ -92,7 +87,6 @@
 
 LOCAL_MODULE := libbootstat_host_debug
 LOCAL_CFLAGS := $(bootstat_debug_cflags)
-LOCAL_CPPFLAGS := $(bootstat_cppflags)
 LOCAL_C_INCLUDES := $(bootstat_c_includes)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_SRC_FILES := $(bootstat_lib_src_files)
@@ -108,7 +102,6 @@
 
 LOCAL_MODULE := bootstat
 LOCAL_CFLAGS := $(bootstat_cflags)
-LOCAL_CPPFLAGS := $(bootstat_cppflags)
 LOCAL_C_INCLUDES := $(bootstat_c_includes)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_STATIC_LIBRARIES := libbootstat
@@ -126,7 +119,6 @@
 
 LOCAL_MODULE := bootstat_tests
 LOCAL_CFLAGS := $(bootstat_tests_cflags)
-LOCAL_CPPFLAGS := $(bootstat_cppflags)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_STATIC_LIBRARIES := libbootstat_debug libgmock
 LOCAL_SRC_FILES := $(bootstat_test_src_files)
@@ -142,7 +134,6 @@
 
 LOCAL_MODULE := bootstat_tests
 LOCAL_CFLAGS := $(bootstat_tests_cflags)
-LOCAL_CPPFLAGS := $(bootstat_cppflags)
 LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
 LOCAL_STATIC_LIBRARIES := libbootstat_host_debug libgmock_host
 LOCAL_SRC_FILES := $(bootstat_test_src_files)
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 40254f8..5d1fae9 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -21,9 +21,11 @@
 #include <sys/stat.h>
 #include <utime.h>
 #include <cstdlib>
+#include <string>
 #include <utility>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include "histogram_logger.h"
 #include "uptime_parser.h"
 
 namespace {
@@ -42,6 +44,20 @@
   }
 
   *uptime = file_stat.st_mtime;
+
+  // The following code (till function exit) is a debug test to ensure the
+  // validity of the file mtime value, i.e., to check that the record file
+  // mtime values are not changed once set.
+  // TODO(jhawkins): Remove this code.
+  std::string content;
+  if (!android::base::ReadFileToString(path, &content)) {
+    PLOG(ERROR) << "Failed to read " << path;
+    return false;
+  }
+
+  int32_t value = std::stoi(content);
+  bootstat::LogHistogram("bootstat_mtime_matches_content", value == *uptime);
+
   return true;
 }
 
@@ -61,8 +77,20 @@
 void BootEventRecordStore::AddBootEventWithValue(
     const std::string& event, int32_t value) {
   std::string record_path = GetBootEventPath(event);
-  if (creat(record_path.c_str(), S_IRUSR | S_IWUSR) == -1) {
+  int record_fd = creat(record_path.c_str(), S_IRUSR | S_IWUSR);
+  if (record_fd == -1) {
     PLOG(ERROR) << "Failed to create " << record_path;
+    return;
+  }
+
+  // Writing the value as content in the record file is a debug measure to
+  // ensure the validity of the file mtime value, i.e., to check that the record
+  // file mtime values are not changed once set.
+  // TODO(jhawkins): Remove this block.
+  if (!android::base::WriteStringToFd(std::to_string(value), record_fd)) {
+    PLOG(ERROR) << "Failed to write value to " << record_path;
+    close(record_fd);
+    return;
   }
 
   // Fill out the stat structure for |record_path| in order to get the atime to
@@ -70,6 +98,8 @@
   struct stat file_stat;
   if (stat(record_path.c_str(), &file_stat) == -1) {
     PLOG(ERROR) << "Failed to read " << record_path;
+    close(record_fd);
+    return;
   }
 
   // Set the |modtime| of the file to store the value of the boot event while
@@ -77,7 +107,11 @@
   struct utimbuf times = {/* actime */ file_stat.st_atime, /* modtime */ value};
   if (utime(record_path.c_str(), &times) == -1) {
     PLOG(ERROR) << "Failed to set mtime for " << record_path;
+    close(record_fd);
+    return;
   }
+
+  close(record_fd);
 }
 
 bool BootEventRecordStore::GetBootEvent(
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index e054844..2639d05 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -32,26 +32,11 @@
 #include <log/log.h>
 #include "boot_event_record_store.h"
 #include "event_log_list_builder.h"
+#include "histogram_logger.h"
 #include "uptime_parser.h"
 
 namespace {
 
-// Builds an EventLog buffer named |event| containing |data| and writes
-// the log into the Tron histogram logs.
-void LogBootEvent(const std::string& event, int32_t data) {
-  LOG(INFO) << "Logging boot metric: " << event << " " << data;
-
-  EventLogListBuilder log_builder;
-  log_builder.Append(event);
-  log_builder.Append(data);
-
-  std::unique_ptr<uint8_t[]> log;
-  size_t size;
-  log_builder.Release(&log, &size);
-
-  android_bWriteLog(HISTOGRAM_LOG_TAG, log.get(), size);
-}
-
 // Scans the boot event record store for record files and logs each boot event
 // via EventLog.
 void LogBootEvents() {
@@ -59,7 +44,7 @@
 
   auto events = boot_event_store.GetAllBootEvents();
   for (auto i = events.cbegin(); i != events.cend(); ++i) {
-    LogBootEvent(i->first, i->second);
+    bootstat::LogHistogram(i->first, i->second);
   }
 }
 
@@ -242,10 +227,10 @@
   static const char* factory_reset_current_time = "factory_reset_current_time";
   if (current_time_utc < 0) {
     // UMA does not display negative values in buckets, so convert to positive.
-    LogBootEvent(factory_reset_current_time, std::abs(current_time_utc));
+    bootstat::LogHistogram(factory_reset_current_time, std::abs(current_time_utc));
     return;
   } else {
-    LogBootEvent(factory_reset_current_time, current_time_utc);
+    bootstat::LogHistogram(factory_reset_current_time, current_time_utc);
   }
 
   // The factory_reset boot event does not exist after the device is reset, so
@@ -261,7 +246,7 @@
   // Calculate and record the difference in time between now and the
   // factory_reset time.
   time_t factory_reset_utc = record.second;
-  LogBootEvent("factory_reset_record_value", factory_reset_utc);
+  bootstat::LogHistogram("factory_reset_record_value", factory_reset_utc);
   time_t time_since_factory_reset = difftime(current_time_utc,
                                              factory_reset_utc);
   boot_event_store.AddBootEventWithValue("time_since_factory_reset",
diff --git a/bootstat/histogram_logger.cpp b/bootstat/histogram_logger.cpp
new file mode 100644
index 0000000..e3aad28
--- /dev/null
+++ b/bootstat/histogram_logger.cpp
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2016 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 "histogram_logger.h"
+
+#include <cstdlib>
+#include <memory>
+#include <android-base/logging.h>
+#include <log/log.h>
+#include "event_log_list_builder.h"
+
+namespace bootstat {
+
+void LogHistogram(const std::string& event, int32_t data) {
+  LOG(INFO) << "Logging histogram: " << event << " " << data;
+
+  EventLogListBuilder log_builder;
+  log_builder.Append(event);
+  log_builder.Append(data);
+
+  std::unique_ptr<uint8_t[]> log;
+  size_t size;
+  log_builder.Release(&log, &size);
+
+  android_bWriteLog(HISTOGRAM_LOG_TAG, log.get(), size);
+}
+
+}  // namespace bootstat
\ No newline at end of file
diff --git a/bootstat/histogram_logger.h b/bootstat/histogram_logger.h
new file mode 100644
index 0000000..60c7776
--- /dev/null
+++ b/bootstat/histogram_logger.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 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 <cstdint>
+#include <string>
+
+namespace bootstat {
+
+// Builds an EventLog buffer named |event| containing |data| and writes
+// the log into the Tron histogram logs.
+void LogHistogram(const std::string& event, int32_t data);
+
+}  // namespace bootstat
\ No newline at end of file
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 97f4096..6064568 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -36,10 +36,10 @@
 
 #include <log/logger.h>
 
+#include <android-base/unique_fd.h>
 #include <cutils/debugger.h>
 #include <cutils/properties.h>
 #include <cutils/sockets.h>
-#include <nativehelper/ScopedFd.h>
 
 #include <linux/input.h>
 
@@ -580,15 +580,24 @@
   siginfo_t siginfo;
   int signal = TEMP_FAILURE_RETRY(sigtimedwait(&signal_set, &siginfo, &timeout));
   if (signal == SIGCHLD) {
-    pid_t rc = waitpid(0, &status, WNOHANG | WUNTRACED);
+    pid_t rc = waitpid(-1, &status, WNOHANG | WUNTRACED);
     if (rc != child_pid) {
       ALOGE("debuggerd: waitpid returned unexpected pid (%d), committing murder-suicide", rc);
+
+      if (WIFEXITED(status)) {
+        ALOGW("debuggerd: pid %d exited with status %d", rc, WEXITSTATUS(status));
+      } else if (WIFSIGNALED(status)) {
+        ALOGW("debuggerd: pid %d received signal %d", rc, WTERMSIG(status));
+      } else if (WIFSTOPPED(status)) {
+        ALOGW("debuggerd: pid %d stopped by signal %d", rc, WSTOPSIG(status));
+      } else if (WIFCONTINUED(status)) {
+        ALOGW("debuggerd: pid %d continued", rc);
+      }
+
       kill_worker = true;
       kill_target = true;
       kill_self = true;
-    }
-
-    if (WIFSIGNALED(status)) {
+    } else if (WIFSIGNALED(status)) {
       ALOGE("debuggerd: worker process %d terminated due to signal %d", child_pid, WTERMSIG(status));
       kill_worker = false;
       kill_target = true;
@@ -612,15 +621,16 @@
     }
   }
 
-  if (kill_target) {
-    // Resume or kill the target, depending on what the initial request was.
-    if (request.action == DEBUGGER_ACTION_CRASH) {
-      ALOGE("debuggerd: killing target %d", request.pid);
-      kill(request.pid, SIGKILL);
-    } else {
-      ALOGE("debuggerd: resuming target %d", request.pid);
-      kill(request.pid, SIGCONT);
-    }
+  int exit_signal = SIGCONT;
+  if (kill_target && request.action == DEBUGGER_ACTION_CRASH) {
+    ALOGE("debuggerd: killing target %d", request.pid);
+    exit_signal = SIGKILL;
+  } else {
+    ALOGW("debuggerd: resuming target %d", request.pid);
+  }
+
+  if (kill(request.pid, exit_signal) != 0) {
+    ALOGE("debuggerd: failed to send signal %d to target: %s", exit_signal, strerror(errno));
   }
 
   if (kill_self) {
@@ -632,7 +642,7 @@
 static void handle_request(int fd) {
   ALOGV("handle_request(%d)\n", fd);
 
-  ScopedFd closer(fd);
+  android::base::unique_fd closer(fd);
   debugger_request_t request;
   memset(&request, 0, sizeof(request));
   int status = read_request(fd, &request);
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 53966d5..e540de2 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -91,6 +91,7 @@
 #define AID_CAMERASERVER  1047  /* cameraserver process */
 #define AID_FIREWALL      1048  /* firewalld process */
 #define AID_TRUNKS        1049  /* trunksd process (TPM daemon) */
+#define AID_NVRAM         1050  /* Access-controlled NVRAM */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
@@ -201,6 +202,7 @@
     { "cameraserver",  AID_CAMERASERVER, },
     { "firewall",      AID_FIREWALL, },
     { "trunks",        AID_TRUNKS, },
+    { "nvram",         AID_NVRAM, },
 
     { "shell",         AID_SHELL, },
     { "cache",         AID_CACHE, },