Merge "Get rid of unneeded allocations in Extract...() APIs"
diff --git a/adb/socket_spec.cpp b/adb/socket_spec.cpp
index 14eb16b..eb4df97 100644
--- a/adb/socket_spec.cpp
+++ b/adb/socket_spec.cpp
@@ -118,7 +118,7 @@
 bool is_socket_spec(const std::string& spec) {
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             return true;
         }
     }
@@ -128,7 +128,7 @@
 bool is_local_socket_spec(const std::string& spec) {
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             return true;
         }
     }
@@ -170,7 +170,7 @@
 
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             if (!it.second.available) {
                 *error = StringPrintf("socket type %s is unavailable on this platform",
                                       it.first.c_str());
@@ -213,7 +213,7 @@
 
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             if (!it.second.available) {
                 *error = StringPrintf("attempted to listen on unavailable socket type: '%s'",
                                       spec.c_str());
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index f93c696..afff2c9 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -42,6 +42,10 @@
 // By default, output goes to logcat on Android and stderr on the host.
 // A process can use `SetLogger` to decide where all logging goes.
 // Implementations are provided for logcat, stderr, and dmesg.
+//
+// By default, the process' name is used as the log tag.
+// Code can choose a specific log tag by defining LOG_TAG
+// before including this header.
 
 // This header also provides assertions:
 //
@@ -63,6 +67,16 @@
 
 #include "android-base/macros.h"
 
+// Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
+#ifdef _LOG_TAG_INTERNAL
+#error "_LOG_TAG_INTERNAL must not be defined"
+#endif
+#ifdef LOG_TAG
+#define _LOG_TAG_INTERNAL LOG_TAG
+#else
+#define _LOG_TAG_INTERNAL nullptr
+#endif
+
 namespace android {
 namespace base {
 
@@ -201,10 +215,10 @@
 
 // Get an ostream that can be used for logging at the given severity and to the
 // given destination. The same notes as for LOG_STREAM apply.
-#define LOG_STREAM_TO(dest, severity)                                   \
-  ::android::base::LogMessage(__FILE__, __LINE__,                       \
-                              ::android::base::dest,                    \
-                              SEVERITY_LAMBDA(severity), -1).stream()
+#define LOG_STREAM_TO(dest, severity)                                           \
+  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,        \
+                              SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, -1) \
+      .stream()
 
 // Logs a message to logcat on Android otherwise to stderr. If the severity is
 // FATAL it also causes an abort. For example:
@@ -231,10 +245,10 @@
 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
 
 // Behaves like PLOG, but logs to the specified log ID.
-#define PLOG_TO(dest, severity)                                              \
-  LOGGING_PREAMBLE(severity) &&                                              \
-      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest, \
-                                  SEVERITY_LAMBDA(severity), errno)          \
+#define PLOG_TO(dest, severity)                                                        \
+  LOGGING_PREAMBLE(severity) &&                                                        \
+      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,           \
+                                  SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, errno) \
           .stream()
 
 // Marker that code is yet to be implemented.
@@ -247,23 +261,26 @@
 //
 //     CHECK(false == true) results in a log message of
 //       "Check failed: false == true".
-#define CHECK(x)                                                                \
-  LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                           \
-      ::android::base::LogMessage(                                              \
-          __FILE__, __LINE__, ::android::base::DEFAULT, ::android::base::FATAL, \
-          -1).stream()                                                          \
+#define CHECK(x)                                                                 \
+  LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                            \
+      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
+                                  ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
+              .stream()                                                          \
           << "Check failed: " #x << " "
 
+// clang-format off
 // Helper for CHECK_xx(x,y) macros.
-#define CHECK_OP(LHS, RHS, OP)                                              \
-  for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);        \
-       UNLIKELY(!(_values.lhs OP _values.rhs));                             \
-       /* empty */)                                                         \
-  ABORT_AFTER_LOG_FATAL                                                     \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
-                              ::android::base::FATAL, -1).stream()          \
-      << "Check failed: " << #LHS << " " << #OP << " " << #RHS              \
-      << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
+#define CHECK_OP(LHS, RHS, OP)                                                                 \
+  for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);                           \
+       UNLIKELY(!(_values.lhs OP _values.rhs));                                                \
+       /* empty */)                                                                            \
+  ABORT_AFTER_LOG_FATAL                                                                        \
+  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,                    \
+                              ::android::base::FATAL, _LOG_TAG_INTERNAL, -1)                   \
+          .stream()                                                                            \
+      << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "=" << _values.lhs \
+      << ", " #RHS "=" << _values.rhs << ") "
+// clang-format on
 
 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
 // of the expressions x and y is evaluated once. Extra logging can be appended
@@ -278,14 +295,17 @@
 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
 
+// clang-format off
 // Helper for CHECK_STRxx(s1,s2) macros.
 #define CHECK_STROP(s1, s2, sense)                                             \
   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
     ABORT_AFTER_LOG_FATAL                                                      \
     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
-                                ::android::base::FATAL, -1).stream()           \
+                                ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
+        .stream()                                                              \
         << "Check failed: " << "\"" << (s1) << "\""                            \
         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
+// clang-format on
 
 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
@@ -400,8 +420,8 @@
 // of a CHECK. The destructor will abort if the severity is FATAL.
 class LogMessage {
  public:
-  LogMessage(const char* file, unsigned int line, LogId id,
-             LogSeverity severity, int error);
+  LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity, const char* tag,
+             int error);
 
   ~LogMessage();
 
@@ -410,12 +430,17 @@
   std::ostream& stream();
 
   // The routine that performs the actual logging.
-  static void LogLine(const char* file, unsigned int line, LogId id,
-                      LogSeverity severity, const char* msg);
+  static void LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                      const char* tag, const char* msg);
 
  private:
   const std::unique_ptr<LogMessageData> data_;
 
+  // TODO(b/35361699): remove these symbols once all prebuilds stop using it.
+  LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity, int error);
+  static void LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                      const char* msg);
+
   DISALLOW_COPY_AND_ASSIGN(LogMessage);
 };
 
diff --git a/base/include/android-base/strings.h b/base/include/android-base/strings.h
index f5f5c11..c11acb1 100644
--- a/base/include/android-base/strings.h
+++ b/base/include/android-base/strings.h
@@ -57,12 +57,18 @@
 extern template std::string Join(const std::vector<const char*>&, const std::string&);
 
 // Tests whether 's' starts with 'prefix'.
+// TODO: string_view
 bool StartsWith(const std::string& s, const char* prefix);
 bool StartsWithIgnoreCase(const std::string& s, const char* prefix);
+bool StartsWith(const std::string& s, const std::string& prefix);
+bool StartsWithIgnoreCase(const std::string& s, const std::string& prefix);
 
 // Tests whether 's' ends with 'suffix'.
+// TODO: string_view
 bool EndsWith(const std::string& s, const char* suffix);
 bool EndsWithIgnoreCase(const std::string& s, const char* suffix);
+bool EndsWith(const std::string& s, const std::string& prefix);
+bool EndsWithIgnoreCase(const std::string& s, const std::string& prefix);
 
 // Tests whether 'lhs' equals 'rhs', ignoring case.
 bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs);
diff --git a/base/logging.cpp b/base/logging.cpp
index 75078e5..0f2012a 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -187,8 +187,8 @@
 }
 #endif
 
-void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
-                  unsigned int line, const char* message) {
+void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
+                  const char* message) {
   struct tm now;
   time_t t = time(nullptr);
 
@@ -205,8 +205,8 @@
   static_assert(arraysize(log_characters) - 1 == FATAL + 1,
                 "Mismatch in size of log_characters and values in LogSeverity");
   char severity_char = log_characters[severity];
-  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
-          severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
+  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", tag ? tag : "nullptr", severity_char, timestamp,
+          getpid(), GetThreadId(), file, line, message);
 }
 
 void DefaultAborter(const char* abort_message) {
@@ -344,14 +344,14 @@
 // checks/logging in a function.
 class LogMessageData {
  public:
-  LogMessageData(const char* file, unsigned int line, LogId id,
-                 LogSeverity severity, int error)
+  LogMessageData(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                 const char* tag, int error)
       : file_(GetFileBasename(file)),
         line_number_(line),
         id_(id),
         severity_(severity),
-        error_(error) {
-  }
+        tag_(tag),
+        error_(error) {}
 
   const char* GetFile() const {
     return file_;
@@ -365,6 +365,8 @@
     return severity_;
   }
 
+  const char* GetTag() const { return tag_; }
+
   LogId GetId() const {
     return id_;
   }
@@ -387,15 +389,19 @@
   const unsigned int line_number_;
   const LogId id_;
   const LogSeverity severity_;
+  const char* const tag_;
   const int error_;
 
   DISALLOW_COPY_AND_ASSIGN(LogMessageData);
 };
 
-LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
-                       LogSeverity severity, int error)
-    : data_(new LogMessageData(file, line, id, severity, error)) {
-}
+LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                       const char* tag, int error)
+    : data_(new LogMessageData(file, line, id, severity, tag, error)) {}
+
+LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                       int error)
+    : LogMessage(file, line, id, severity, nullptr, error) {}
 
 LogMessage::~LogMessage() {
   // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
@@ -413,16 +419,16 @@
     // Do the actual logging with the lock held.
     std::lock_guard<std::mutex> lock(LoggingLock());
     if (msg.find('\n') == std::string::npos) {
-      LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-              data_->GetSeverity(), msg.c_str());
+      LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
+              data_->GetTag(), msg.c_str());
     } else {
       msg += '\n';
       size_t i = 0;
       while (i < msg.size()) {
         size_t nl = msg.find('\n', i);
         msg[nl] = '\0';
-        LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-                data_->GetSeverity(), &msg[i]);
+        LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
+                data_->GetTag(), &msg[i]);
         // Undo the zero-termination so we can give the complete message to the aborter.
         msg[nl] = '\n';
         i = nl + 1;
@@ -440,12 +446,17 @@
   return data_->GetBuffer();
 }
 
-void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
-                         LogSeverity severity, const char* message) {
-  const char* tag = ProgramInvocationName().c_str();
+void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                         const char* tag, const char* message) {
+  if (tag == nullptr) tag = ProgramInvocationName().c_str();
   Logger()(id, severity, tag, file, line, message);
 }
 
+void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                         const char* message) {
+  LogLine(file, line, id, severity, nullptr, message);
+}
+
 LogSeverity GetMinimumLogSeverity() {
     return gMinimumLogSeverity;
 }
diff --git a/base/strings.cpp b/base/strings.cpp
index bfdaf12..a8bb2a9 100644
--- a/base/strings.cpp
+++ b/base/strings.cpp
@@ -91,12 +91,20 @@
   return strncmp(s.c_str(), prefix, strlen(prefix)) == 0;
 }
 
+bool StartsWith(const std::string& s, const std::string& prefix) {
+  return strncmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
+}
+
 bool StartsWithIgnoreCase(const std::string& s, const char* prefix) {
   return strncasecmp(s.c_str(), prefix, strlen(prefix)) == 0;
 }
 
-static bool EndsWith(const std::string& s, const char* suffix, bool case_sensitive) {
-  size_t suffix_length = strlen(suffix);
+bool StartsWithIgnoreCase(const std::string& s, const std::string& prefix) {
+  return strncasecmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
+}
+
+static bool EndsWith(const std::string& s, const char* suffix, size_t suffix_length,
+                     bool case_sensitive) {
   size_t string_length = s.size();
   if (suffix_length > string_length) {
     return false;
@@ -106,11 +114,19 @@
 }
 
 bool EndsWith(const std::string& s, const char* suffix) {
-  return EndsWith(s, suffix, true);
+  return EndsWith(s, suffix, strlen(suffix), true);
+}
+
+bool EndsWith(const std::string& s, const std::string& suffix) {
+  return EndsWith(s, suffix.c_str(), suffix.size(), true);
 }
 
 bool EndsWithIgnoreCase(const std::string& s, const char* suffix) {
-  return EndsWith(s, suffix, false);
+  return EndsWith(s, suffix, strlen(suffix), false);
+}
+
+bool EndsWithIgnoreCase(const std::string& s, const std::string& suffix) {
+  return EndsWith(s, suffix.c_str(), suffix.size(), false);
 }
 
 bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs) {
diff --git a/base/strings_test.cpp b/base/strings_test.cpp
index 121197c..b8639ea 100644
--- a/base/strings_test.cpp
+++ b/base/strings_test.cpp
@@ -253,6 +253,26 @@
   ASSERT_FALSE(android::base::EndsWithIgnoreCase("foobar", "FOO"));
 }
 
+TEST(strings, StartsWith_std_string) {
+  ASSERT_TRUE(android::base::StartsWith("hello", std::string{"hell"}));
+  ASSERT_FALSE(android::base::StartsWith("goodbye", std::string{"hell"}));
+}
+
+TEST(strings, StartsWithIgnoreCase_std_string) {
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("HeLlO", std::string{"hell"}));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("GoOdByE", std::string{"hell"}));
+}
+
+TEST(strings, EndsWith_std_string) {
+  ASSERT_TRUE(android::base::EndsWith("hello", std::string{"lo"}));
+  ASSERT_FALSE(android::base::EndsWith("goodbye", std::string{"lo"}));
+}
+
+TEST(strings, EndsWithIgnoreCase_std_string) {
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("HeLlO", std::string{"lo"}));
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("GoOdByE", std::string{"lo"}));
+}
+
 TEST(strings, EqualsIgnoreCase) {
   ASSERT_TRUE(android::base::EqualsIgnoreCase("foo", "FOO"));
   ASSERT_TRUE(android::base::EqualsIgnoreCase("FOO", "foo"));
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index b19ab78..a1fcad8 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -315,8 +315,7 @@
   for (auto& s : knownReasons) {
     if (s == "cold") break;
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
@@ -328,8 +327,7 @@
   for (auto& s : knownReasons) {
     if (s == "recovery") break;
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
@@ -340,8 +338,7 @@
 bool isKnownRebootReason(const std::string& r) {
   for (auto& s : knownReasons) {
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
@@ -432,9 +429,11 @@
     if (needle.length() > pos) return std::string::npos;
     pos -= needle.length();
     // fuzzy match to maximum kBitErrorRate
-    do {
+    for (;;) {
       if (numError(pos, needle) != std::string::npos) return pos;
-    } while (pos-- != 0);
+      if (pos == 0) break;
+      --pos;
+    }
     return std::string::npos;
   }
 
diff --git a/init/action.cpp b/init/action.cpp
index 5fa6bec..ab51eea 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -358,7 +358,7 @@
     Subcontext* action_subcontext = nullptr;
     if (subcontexts_) {
         for (auto& subcontext : *subcontexts_) {
-            if (StartsWith(filename, subcontext.path_prefix().c_str())) {
+            if (StartsWith(filename, subcontext.path_prefix())) {
                 action_subcontext = &subcontext;
                 break;
             }
diff --git a/init/devices.cpp b/init/devices.cpp
index af6b50a..8d27f4f 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -127,7 +127,7 @@
 }
 
 bool Permissions::Match(const std::string& path) const {
-    if (prefix_) return StartsWith(path, name_.c_str());
+    if (prefix_) return StartsWith(path, name_);
     if (wildcard_) return fnmatch(name_.c_str(), path.c_str(), FNM_PATHNAME) == 0;
     return path == name_;
 }
@@ -300,9 +300,9 @@
         static const std::string devices_platform_prefix = "/devices/platform/";
         static const std::string devices_prefix = "/devices/";
 
-        if (StartsWith(device, devices_platform_prefix.c_str())) {
+        if (StartsWith(device, devices_platform_prefix)) {
             device = device.substr(devices_platform_prefix.length());
-        } else if (StartsWith(device, devices_prefix.c_str())) {
+        } else if (StartsWith(device, devices_prefix)) {
             device = device.substr(devices_prefix.length());
         }
 
diff --git a/init/parser.cpp b/init/parser.cpp
index 6ddb09f..4c69bac 100644
--- a/init/parser.cpp
+++ b/init/parser.cpp
@@ -76,7 +76,7 @@
                 // current section parsers.  This is meant for /sys/ and /dev/ line entries for
                 // uevent.
                 for (const auto& [prefix, callback] : line_callbacks_) {
-                    if (android::base::StartsWith(args[0], prefix.c_str())) {
+                    if (android::base::StartsWith(args[0], prefix)) {
                         end_section();
 
                         if (auto result = callback(std::move(args)); !result) {
diff --git a/init/service.cpp b/init/service.cpp
index 331b859..a4e33f7 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -1125,7 +1125,7 @@
     Subcontext* restart_action_subcontext = nullptr;
     if (subcontexts_) {
         for (auto& subcontext : *subcontexts_) {
-            if (StartsWith(filename, subcontext.path_prefix().c_str())) {
+            if (StartsWith(filename, subcontext.path_prefix())) {
                 restart_action_subcontext = &subcontext;
                 break;
             }
diff --git a/libcutils/tests/fs_config.cpp b/libcutils/tests/fs_config.cpp
index 391adb6..d5dc66a 100644
--- a/libcutils/tests/fs_config.cpp
+++ b/libcutils/tests/fs_config.cpp
@@ -81,7 +81,7 @@
         }
 
         // check if path is <partition>/
-        if (android::base::StartsWith(path, prefix.c_str())) {
+        if (android::base::StartsWith(path, prefix)) {
             // rebuild path to be system/<partition>/... to check for alias
             path = alternate + path.substr(prefix.size());
             for (second = 0; second < paths.size(); ++second) {
@@ -97,7 +97,7 @@
         }
 
         // check if path is system/<partition>/
-        if (android::base::StartsWith(path, alternate.c_str())) {
+        if (android::base::StartsWith(path, alternate)) {
             // rebuild path to be <partition>/... to check for alias
             path = prefix + path.substr(alternate.size());
             for (second = 0; second < paths.size(); ++second) {
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index 8c8d064..e9f0c0f 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -382,7 +382,7 @@
                   config_file_path, &sonames,
                   [&company_name](const std::string& soname, std::string* error_msg) {
                     if (android::base::StartsWith(soname, "lib") &&
-                        android::base::EndsWith(soname, ("." + company_name + ".so").c_str())) {
+                        android::base::EndsWith(soname, "." + company_name + ".so")) {
                       return true;
                     } else {
                       *error_msg = "Library name \"" + soname +
diff --git a/libsuspend/Android.bp b/libsuspend/Android.bp
index 32f1e1f..fa06dc4 100644
--- a/libsuspend/Android.bp
+++ b/libsuspend/Android.bp
@@ -9,7 +9,7 @@
 
     srcs: [
         "autosuspend.c",
-        "autosuspend_wakeup_count.c",
+        "autosuspend_wakeup_count.cpp",
     ],
     export_include_dirs: ["include"],
     local_include_dirs: ["include"],
diff --git a/libsuspend/autosuspend_ops.h b/libsuspend/autosuspend_ops.h
index 2f435d9..357b828 100644
--- a/libsuspend/autosuspend_ops.h
+++ b/libsuspend/autosuspend_ops.h
@@ -23,6 +23,8 @@
     void (*set_wakeup_callback)(void (*func)(bool success));
 };
 
+__BEGIN_DECLS
 struct autosuspend_ops *autosuspend_wakeup_count_init(void);
+__END_DECLS
 
 #endif
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.cpp
similarity index 97%
rename from libsuspend/autosuspend_wakeup_count.c
rename to libsuspend/autosuspend_wakeup_count.cpp
index 81cb44c..30f8427 100644
--- a/libsuspend/autosuspend_wakeup_count.c
+++ b/libsuspend/autosuspend_wakeup_count.cpp
@@ -21,8 +21,8 @@
 #include <fcntl.h>
 #include <pthread.h>
 #include <semaphore.h>
-#include <stddef.h>
 #include <stdbool.h>
+#include <stddef.h>
 #include <string.h>
 #include <sys/param.h>
 #include <sys/stat.h>
@@ -68,8 +68,8 @@
         success = false;
         ALOGV("%s: read wakeup_count", __func__);
         lseek(wakeup_count_fd, 0, SEEK_SET);
-        wakeup_count_len = TEMP_FAILURE_RETRY(read(wakeup_count_fd, wakeup_count,
-                sizeof(wakeup_count)));
+        wakeup_count_len =
+            TEMP_FAILURE_RETRY(read(wakeup_count_fd, wakeup_count, sizeof(wakeup_count)));
         if (wakeup_count_len < 0) {
             strerror_r(errno, buf, sizeof(buf));
             ALOGE("Error reading from %s: %s", SYS_POWER_WAKEUP_COUNT, buf);
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index fad899f..133f3b9 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -215,6 +215,15 @@
     ],
 }
 
+cc_binary {
+    name: "unwind_for_offline",
+    defaults: ["libunwindstack_tools"],
+
+    srcs: [
+        "tools/unwind_for_offline.cpp",
+    ],
+}
+
 // Generates the elf data for use in the tests for .gnu_debugdata frames.
 // Once these files are generated, use the xz command to compress the data.
 cc_binary_host {
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
index 1f3c6c3..285f879 100644
--- a/libunwindstack/Memory.cpp
+++ b/libunwindstack/Memory.cpp
@@ -35,10 +35,6 @@
 namespace unwindstack {
 
 static size_t ProcessVmRead(pid_t pid, uint64_t remote_src, void* dst, size_t len) {
-  struct iovec dst_iov = {
-      .iov_base = dst,
-      .iov_len = len,
-  };
 
   // Split up the remote read across page boundaries.
   // From the manpage:
@@ -49,39 +45,49 @@
   //   perform a partial transfer that splits a single iovec element.
   constexpr size_t kMaxIovecs = 64;
   struct iovec src_iovs[kMaxIovecs];
-  size_t iovecs_used = 0;
 
   uint64_t cur = remote_src;
+  size_t total_read = 0;
   while (len > 0) {
-    if (iovecs_used == kMaxIovecs) {
-      errno = EINVAL;
-      return 0;
+    struct iovec dst_iov = {
+        .iov_base = &reinterpret_cast<uint8_t*>(dst)[total_read], .iov_len = len,
+    };
+
+    size_t iovecs_used = 0;
+    while (len > 0) {
+      if (iovecs_used == kMaxIovecs) {
+        break;
+      }
+
+      // struct iovec uses void* for iov_base.
+      if (cur >= UINTPTR_MAX) {
+        errno = EFAULT;
+        return total_read;
+      }
+
+      src_iovs[iovecs_used].iov_base = reinterpret_cast<void*>(cur);
+
+      uintptr_t misalignment = cur & (getpagesize() - 1);
+      size_t iov_len = getpagesize() - misalignment;
+      iov_len = std::min(iov_len, len);
+
+      len -= iov_len;
+      if (__builtin_add_overflow(cur, iov_len, &cur)) {
+        errno = EFAULT;
+        return total_read;
+      }
+
+      src_iovs[iovecs_used].iov_len = iov_len;
+      ++iovecs_used;
     }
 
-    // struct iovec uses void* for iov_base.
-    if (cur >= UINTPTR_MAX) {
-      errno = EFAULT;
-      return 0;
+    ssize_t rc = process_vm_readv(pid, &dst_iov, 1, src_iovs, iovecs_used, 0);
+    if (rc == -1) {
+      return total_read;
     }
-
-    src_iovs[iovecs_used].iov_base = reinterpret_cast<void*>(cur);
-
-    uintptr_t misalignment = cur & (getpagesize() - 1);
-    size_t iov_len = getpagesize() - misalignment;
-    iov_len = std::min(iov_len, len);
-
-    len -= iov_len;
-    if (__builtin_add_overflow(cur, iov_len, &cur)) {
-      errno = EFAULT;
-      return 0;
-    }
-
-    src_iovs[iovecs_used].iov_len = iov_len;
-    ++iovecs_used;
+    total_read += rc;
   }
-
-  ssize_t rc = process_vm_readv(pid, &dst_iov, 1, src_iovs, iovecs_used, 0);
-  return rc == -1 ? 0 : rc;
+  return total_read;
 }
 
 static bool PtraceReadLong(pid_t pid, uint64_t addr, long* value) {
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
index f5492a2..fb56e8a 100644
--- a/libunwindstack/tests/MemoryRemoteTest.cpp
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -79,6 +79,35 @@
   ASSERT_TRUE(Detach(pid));
 }
 
+TEST_F(MemoryRemoteTest, read_large) {
+  static constexpr size_t kTotalPages = 245;
+  std::vector<uint8_t> src(kTotalPages * getpagesize());
+  for (size_t i = 0; i < kTotalPages; i++) {
+    memset(&src[i * getpagesize()], i, getpagesize());
+  }
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true)
+      ;
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+  TestScopedPidReaper reap(pid);
+
+  ASSERT_TRUE(Attach(pid));
+
+  MemoryRemote remote(pid);
+
+  std::vector<uint8_t> dst(kTotalPages * getpagesize());
+  ASSERT_TRUE(remote.ReadFully(reinterpret_cast<uint64_t>(src.data()), dst.data(), src.size()));
+  for (size_t i = 0; i < kTotalPages * getpagesize(); i++) {
+    ASSERT_EQ(i / getpagesize(), dst[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_TRUE(Detach(pid));
+}
+
 TEST_F(MemoryRemoteTest, read_partial) {
   char* mapping = static_cast<char*>(
       mmap(nullptr, 4 * getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
diff --git a/libunwindstack/tools/unwind_for_offline.cpp b/libunwindstack/tools/unwind_for_offline.cpp
new file mode 100644
index 0000000..d64ef8f
--- /dev/null
+++ b/libunwindstack/tools/unwind_for_offline.cpp
@@ -0,0 +1,262 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#define _GNU_SOURCE 1
+#include <errno.h>
+#include <inttypes.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <unwindstack/Elf.h>
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
+#include <unwindstack/Unwinder.h>
+
+#include <android-base/stringprintf.h>
+
+struct map_info_t {
+  uint64_t start;
+  uint64_t end;
+  uint64_t offset;
+  std::string name;
+};
+
+static bool Attach(pid_t pid) {
+  if (ptrace(PTRACE_ATTACH, pid, 0, 0) == -1) {
+    return false;
+  }
+
+  // Allow at least 1 second to attach properly.
+  for (size_t i = 0; i < 1000; i++) {
+    siginfo_t si;
+    if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
+      return true;
+    }
+    usleep(1000);
+  }
+  printf("%d: Failed to stop.\n", pid);
+  return false;
+}
+
+bool SaveRegs(unwindstack::Regs* regs) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("regs.txt", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create file regs.txt.\n");
+    return false;
+  }
+  regs->IterateRegisters([&fp](const char* name, uint64_t value) {
+    fprintf(fp.get(), "%s: %" PRIx64 "\n", name, value);
+  });
+
+  return true;
+}
+
+bool SaveStack(pid_t pid, uint64_t sp_start, uint64_t sp_end) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("stack.data", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create stack.data.\n");
+    return false;
+  }
+
+  size_t bytes = fwrite(&sp_start, 1, sizeof(sp_start), fp.get());
+  if (bytes != sizeof(sp_start)) {
+    perror("Failed to write all data.");
+    return false;
+  }
+
+  std::vector<uint8_t> buffer(sp_end - sp_start);
+  auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
+  if (!process_memory->Read(sp_start, buffer.data(), buffer.size())) {
+    printf("Unable to read stack data.\n");
+    return false;
+  }
+
+  bytes = fwrite(buffer.data(), 1, buffer.size(), fp.get());
+  if (bytes != buffer.size()) {
+    printf("Failed to write all stack data: stack size %zu, written %zu\n", buffer.size(), bytes);
+    return 1;
+  }
+
+  return true;
+}
+
+bool CreateElfFromMemory(std::shared_ptr<unwindstack::Memory>& memory, map_info_t* info) {
+  std::string cur_name;
+  if (info->name.empty()) {
+    cur_name = android::base::StringPrintf("anonymous:%" PRIx64, info->start);
+  } else {
+    cur_name = basename(info->name.c_str());
+    cur_name = android::base::StringPrintf("%s:%" PRIx64, basename(info->name.c_str()), info->start);
+  }
+
+  std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
+  if (output == nullptr) {
+    printf("Cannot create %s\n", cur_name.c_str());
+    return false;
+  }
+  std::vector<uint8_t> buffer(info->end - info->start);
+  // If this is a mapped in file, it might not be possible to read the entire
+  // map, so read all that is readable.
+  size_t bytes = memory->Read(info->start, buffer.data(), buffer.size());
+  if (bytes == 0) {
+    printf("Cannot read data from address %" PRIx64 " length %zu\n", info->start, buffer.size());
+    return false;
+  }
+  size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
+  if (bytes_written != bytes) {
+    printf("Failed to write all data to file: bytes read %zu, written %zu\n", bytes, bytes_written);
+    return false;
+  }
+
+  // Replace the name with the new name.
+  info->name = cur_name;
+
+  return true;
+}
+
+bool CopyElfFromFile(map_info_t* info) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(info->name.c_str(), "r"), &fclose);
+  if (fp == nullptr) {
+    return false;
+  }
+
+  std::string cur_name = basename(info->name.c_str());
+  std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
+  if (output == nullptr) {
+    printf("Cannot create file %s\n", cur_name.c_str());
+    return false;
+  }
+  std::vector<uint8_t> buffer(10000);
+  size_t bytes;
+  while ((bytes = fread(buffer.data(), 1, buffer.size(), fp.get())) > 0) {
+    size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
+    if (bytes_written != bytes) {
+      printf("Bytes written doesn't match bytes read: read %zu, written %zu\n", bytes,
+             bytes_written);
+      return false;
+    }
+  }
+
+  // Replace the name with the new name.
+  info->name = cur_name;
+
+  return true;
+}
+
+int SaveData(pid_t pid) {
+  unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(pid);
+  if (regs == nullptr) {
+    printf("Unable to get remote reg data.\n");
+    return 1;
+  }
+
+  unwindstack::RemoteMaps maps(pid);
+  if (!maps.Parse()) {
+    printf("Unable to parse maps.\n");
+    return 1;
+  }
+
+  // Save the current state of the registers.
+  if (!SaveRegs(regs)) {
+    return 1;
+  }
+
+  // Do an unwind so we know how much of the stack to save, and what
+  // elf files are involved.
+  uint64_t sp = regs->sp();
+  auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
+  unwindstack::Unwinder unwinder(1024, &maps, regs, process_memory);
+  unwinder.Unwind();
+
+  std::unordered_map<uint64_t, map_info_t> maps_by_start;
+  uint64_t last_sp;
+  for (auto frame : unwinder.frames()) {
+    last_sp = frame.sp;
+    if (maps_by_start.count(frame.map_start) == 0) {
+      auto info = &maps_by_start[frame.map_start];
+      info->start = frame.map_start;
+      info->end = frame.map_end;
+      info->offset = frame.map_offset;
+      info->name = frame.map_name;
+      if (!CopyElfFromFile(info)) {
+        // Try to create the elf from memory, this will handle cases where
+        // the data only exists in memory such as vdso data on x86.
+        if (!CreateElfFromMemory(process_memory, info)) {
+          return 1;
+        }
+      }
+    }
+  }
+
+  if (!SaveStack(pid, sp, last_sp)) {
+    return 1;
+  }
+
+  std::vector<std::pair<uint64_t, map_info_t>> sorted_maps(maps_by_start.begin(),
+                                                           maps_by_start.end());
+  std::sort(sorted_maps.begin(), sorted_maps.end(),
+            [](auto& a, auto& b) { return a.first < b.first; });
+
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("maps.txt", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create maps.txt.\n");
+    return false;
+  }
+
+  for (auto& element : sorted_maps) {
+    map_info_t& map = element.second;
+    fprintf(fp.get(), "%" PRIx64 "-%" PRIx64 " r-xp %" PRIx64 " 00:00 0", map.start, map.end,
+            map.offset);
+    if (!map.name.empty()) {
+      fprintf(fp.get(), "   %s", map.name.c_str());
+    }
+    fprintf(fp.get(), "\n");
+  }
+
+  return 0;
+}
+
+int main(int argc, char** argv) {
+  if (argc != 2) {
+    printf("Usage: unwind_for_offline <PID>\n");
+    return 1;
+  }
+
+  pid_t pid = atoi(argv[1]);
+  if (!Attach(pid)) {
+    printf("Failed to attach to pid %d: %s\n", pid, strerror(errno));
+    return 1;
+  }
+
+  int return_code = SaveData(pid);
+
+  ptrace(PTRACE_DETACH, pid, 0, 0);
+
+  return return_code;
+}
diff --git a/libusbhost/include/usbhost/usbhost.h b/libusbhost/include/usbhost/usbhost.h
index a8dd673..9758b18 100644
--- a/libusbhost/include/usbhost/usbhost.h
+++ b/libusbhost/include/usbhost/usbhost.h
@@ -140,8 +140,26 @@
 const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device);
 
 /* Returns a USB descriptor string for the given string ID.
+ * Return value: < 0 on error.  0 on success.
+ * The string is returned in ucs2_out in USB-native UCS-2 encoding.
+ *
+ * parameters:
+ *  id - the string descriptor index.
+ *  timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
+ *  ucs2_out - Must point to null on call.
+ *             Will be filled in with a buffer on success.
+ *             If this is non-null on return, it must be free()d.
+ *  response_size - size, in bytes, of ucs-2 string in ucs2_out.
+ *                  The size isn't guaranteed to include null termination.
+ * Call free() to free the result when you are done with it.
+ */
+int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
+                               size_t* response_size);
+
+/* Returns a USB descriptor string for the given string ID.
  * Used to implement usb_device_get_manufacturer_name,
  * usb_device_get_product_name and usb_device_get_serial.
+ * Returns ascii - non ascii characters will be replaced with '?'.
  * Call free() to free the result when you are done with it.
  */
 char* usb_device_get_string(struct usb_device *device, int id, int timeout);
diff --git a/libusbhost/usbhost.c b/libusbhost/usbhost.c
index 4d286bf..fa0191b 100644
--- a/libusbhost/usbhost.c
+++ b/libusbhost/usbhost.c
@@ -464,17 +464,30 @@
     return (struct usb_device_descriptor*)device->desc;
 }
 
-char* usb_device_get_string(struct usb_device *device, int id, int timeout)
-{
-    char string[256];
-    __u16 buffer[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
+/* Returns a USB descriptor string for the given string ID.
+ * Return value: < 0 on error.  0 on success.
+ * The string is returned in ucs2_out in USB-native UCS-2 encoding.
+ *
+ * parameters:
+ *  id - the string descriptor index.
+ *  timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
+ *  ucs2_out - Must point to null on call.
+ *             Will be filled in with a buffer on success.
+ *             If this is non-null on return, it must be free()d.
+ *  response_size - size, in bytes, of ucs-2 string in ucs2_out.
+ *                  The size isn't guaranteed to include null termination.
+ * Call free() to free the result when you are done with it.
+ */
+int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
+                               size_t* response_size) {
     __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
-    int i, result;
+    char response[MAX_STRING_DESCRIPTOR_LENGTH];
+    int result;
     int languageCount = 0;
 
-    if (id == 0) return NULL;
+    if (id == 0) return -1;
+    if (*ucs2_out != NULL) return -1;
 
-    string[0] = 0;
     memset(languages, 0, sizeof(languages));
 
     // read list of supported languages
@@ -485,25 +498,54 @@
     if (result > 0)
         languageCount = (result - 2) / 2;
 
-    for (i = 1; i <= languageCount; i++) {
-        memset(buffer, 0, sizeof(buffer));
+    for (int i = 1; i <= languageCount; i++) {
+        memset(response, 0, sizeof(response));
 
-        result = usb_device_control_transfer(device,
-                USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
-                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer),
-                timeout);
-        if (result > 0) {
-            int i;
-            // skip first word, and copy the rest to the string, changing shorts to bytes.
-            result /= 2;
-            for (i = 1; i < result; i++)
-                string[i - 1] = buffer[i];
-            string[i - 1] = 0;
-            return strdup(string);
+        result = usb_device_control_transfer(
+            device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
+            (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
+        if (result >= 2) {  // string contents begin at offset 2.
+            int descriptor_len = result - 2;
+            char* out = malloc(descriptor_len + 3);
+            if (out == NULL) {
+                return -1;
+            }
+            memcpy(out, response + 2, descriptor_len);
+            // trail with three additional NULLs, so that there's guaranteed
+            // to be a UCS-2 NULL character beyond whatever USB returned.
+            // The returned string length is still just what USB returned.
+            memset(out + descriptor_len, '\0', 3);
+            *ucs2_out = (void*)out;
+            *response_size = descriptor_len;
+            return 0;
         }
     }
+    return -1;
+}
 
-    return NULL;
+/* Warning: previously this blindly returned the lower 8 bits of
+ * every UCS-2 character in a USB descriptor.  Now it will replace
+ * values > 127 with ascii '?'.
+ */
+char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
+    char* ascii_string = NULL;
+    size_t raw_string_len = 0;
+    size_t i;
+    if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
+        return NULL;
+    if (ascii_string == NULL) return NULL;
+    for (i = 0; i < raw_string_len / 2; ++i) {
+        // wire format for USB is always little-endian.
+        char lower = ascii_string[2 * i];
+        char upper = ascii_string[2 * i + 1];
+        if (upper || (lower & 0x80)) {
+            ascii_string[i] = '?';
+        } else {
+            ascii_string[i] = lower;
+        }
+    }
+    ascii_string[i] = '\0';
+    return ascii_string;
 }
 
 char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index cb72f0e..466be4a 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -64,11 +64,6 @@
   return OpenArchive(abs_path.c_str(), handle);
 }
 
-static void AssertNameEquals(const std::string& name_str, const ZipString& name) {
-  ASSERT_EQ(name_str.size(), name.name_length);
-  ASSERT_EQ(0, memcmp(name_str.c_str(), name.name, name.name_length));
-}
-
 static void SetZipString(ZipString* zip_str, const std::string& str) {
   zip_str->name = reinterpret_cast<const uint8_t*>(str.c_str());
   zip_str->name_length = str.size();
@@ -117,132 +112,60 @@
   close(fd);
 }
 
-TEST(ziparchive, Iteration) {
+static void AssertIterationOrder(const ZipString* prefix, const ZipString* suffix,
+                                 const std::vector<std::string>& expected_names_sorted) {
   ZipArchiveHandle handle;
   ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
 
   void* iteration_cookie;
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, nullptr, nullptr));
+  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, prefix, suffix));
 
   ZipEntry data;
+  std::vector<std::string> names;
+
   ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // a.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("a.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // b/
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/", name);
+  for (size_t i = 0; i < expected_names_sorted.size(); ++i) {
+    ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
+    names.push_back(std::string(reinterpret_cast<const char*>(name.name), name.name_length));
+  }
 
   // End of iteration.
   ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
   CloseArchive(handle);
+
+  // Assert that the names are as expected.
+  std::sort(names.begin(), names.end());
+  ASSERT_EQ(expected_names_sorted, names);
+}
+
+TEST(ziparchive, Iteration) {
+  static const std::vector<std::string> kExpectedMatchesSorted = {"a.txt", "b.txt", "b/", "b/c.txt",
+                                                                  "b/d.txt"};
+
+  AssertIterationOrder(nullptr, nullptr, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithPrefix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString prefix("b/");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, &prefix, nullptr));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"b/", "b/c.txt", "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // b/
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(&prefix, nullptr, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithSuffix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString suffix(".txt");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, nullptr, &suffix));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"a.txt", "b.txt", "b/c.txt",
+                                                                  "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // a.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("a.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(nullptr, &suffix, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithPrefixAndSuffix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString prefix("b");
   ZipString suffix(".txt");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, &prefix, &suffix));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"b.txt", "b/c.txt", "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(&prefix, &suffix, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithBadPrefixAndSuffix) {
diff --git a/rootdir/etc/ld.config.txt.in b/rootdir/etc/ld.config.txt.in
index df26f90..7036356 100644
--- a/rootdir/etc/ld.config.txt.in
+++ b/rootdir/etc/ld.config.txt.in
@@ -218,7 +218,7 @@
 # (LL-NDK only) access.
 ###############################################################################
 [vendor]
-additional.namespaces = system
+additional.namespaces = system,vndk
 
 ###############################################################################
 # "default" namespace
@@ -261,10 +261,39 @@
 namespace.default.asan.permitted.paths += /data/asan/vendor
 namespace.default.asan.permitted.paths +=           /vendor
 
-namespace.default.links = system
-namespace.default.link.system.shared_libs  = %LLNDK_LIBRARIES%
-namespace.default.link.system.shared_libs += %VNDK_SAMEPROCESS_LIBRARIES%
-namespace.default.link.system.shared_libs += %VNDK_CORE_LIBRARIES%
+namespace.default.links = system,vndk
+namespace.default.link.system.shared_libs = %LLNDK_LIBRARIES%
+namespace.default.link.vndk.shared_libs  = %VNDK_SAMEPROCESS_LIBRARIES%
+namespace.default.link.vndk.shared_libs += %VNDK_CORE_LIBRARIES%
+
+###############################################################################
+# "vndk" namespace
+#
+# This namespace is where VNDK and VNDK-SP libraries are loaded for
+# a vendor process.
+###############################################################################
+namespace.vndk.isolated = false
+
+namespace.vndk.search.paths  = /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.search.paths += /system/${LIB}/vndk${VNDK_VER}
+
+# This is exceptionally required since android.hidl.memory@1.0-impl.so is here
+namespace.vndk.permitted.paths = /system/${LIB}/vndk-sp${VNDK_VER}/hw
+
+namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}/hw
+namespace.vndk.asan.permitted.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}/hw
+
+namespace.vndk.asan.search.paths  = /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk${VNDK_VER}
+
+# When these NDK libs are required inside this namespace, then it is redirected
+# to the system namespace. This is possible since their ABI is stable across
+# Android releases.
+namespace.vndk.links = system
+namespace.vndk.link.system.shared_libs  = %LLNDK_LIBRARIES%
+namespace.vndk.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "system" namespace
@@ -274,13 +303,7 @@
 ###############################################################################
 namespace.system.isolated = false
 
-namespace.system.search.paths  = /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.search.paths += /system/${LIB}/vndk${VNDK_VER}
-namespace.system.search.paths += /system/${LIB}
+namespace.system.search.paths = /system/${LIB}
 
-namespace.system.asan.search.paths  = /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
-namespace.system.asan.search.paths +=           /system/${LIB}/vndk${VNDK_VER}
-namespace.system.asan.search.paths += /data/asan/system/${LIB}
+namespace.system.asan.search.paths  = /data/asan/system/${LIB}
 namespace.system.asan.search.paths +=           /system/${LIB}
diff --git a/trusty/OWNERS b/trusty/OWNERS
index 25291fd..357b4f4 100644
--- a/trusty/OWNERS
+++ b/trusty/OWNERS
@@ -1 +1,3 @@
 bohr@google.com
+swillden@google.com
+dkrahn@google.com