Merge "liblog: fix benchmark build after google-benchmark upgrade."
diff --git a/base/Android.bp b/base/Android.bp
index 58d3a50..25a9f68 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -141,6 +141,7 @@
         "parsenetaddress_test.cpp",
         "properties_test.cpp",
         "quick_exit_test.cpp",
+        "result_test.cpp",
         "scopeguard_test.cpp",
         "stringprintf_test.cpp",
         "strings_test.cpp",
diff --git a/base/expected_test.cpp b/base/expected_test.cpp
index 490ced4..a74bc1d 100644
--- a/base/expected_test.cpp
+++ b/base/expected_test.cpp
@@ -29,6 +29,7 @@
 typedef expected<double, double> exp_double;
 typedef expected<std::string, std::string> exp_string;
 typedef expected<std::pair<std::string, int>, int> exp_pair;
+typedef expected<void, int> exp_void;
 
 struct T {
   int a;
@@ -59,6 +60,9 @@
   exp_complex e2;
   EXPECT_TRUE(e2.has_value());
   EXPECT_EQ(T(0,0), e2.value());
+
+  exp_void e3;
+  EXPECT_TRUE(e3.has_value());
 }
 
 TEST(Expected, testCopyConstructible) {
@@ -69,6 +73,11 @@
   EXPECT_TRUE(e2.has_value());
   EXPECT_EQ(0, e.value());
   EXPECT_EQ(0, e2.value());
+
+  exp_void e3;
+  exp_void e4 = e3;
+  EXPECT_TRUE(e3.has_value());
+  EXPECT_TRUE(e4.has_value());
 }
 
 TEST(Expected, testMoveConstructible) {
@@ -87,6 +96,11 @@
   EXPECT_TRUE(e4.has_value());
   EXPECT_EQ("", e3.value()); // e3 is moved
   EXPECT_EQ("hello", e4.value());
+
+  exp_void e5;
+  exp_void e6 = std::move(e5);
+  EXPECT_TRUE(e5.has_value());
+  EXPECT_TRUE(e6.has_value());
 }
 
 TEST(Expected, testCopyConstructibleFromConvertibleType) {
@@ -114,11 +128,13 @@
   exp_double e2 = 5.5f;
   exp_string e3 = std::string("hello");
   exp_complex e4 = T(10, 20);
+  exp_void e5 = {};
 
   EXPECT_TRUE(e.has_value());
   EXPECT_TRUE(e2.has_value());
   EXPECT_TRUE(e3.has_value());
   EXPECT_TRUE(e4.has_value());
+  EXPECT_TRUE(e5.has_value());
   EXPECT_EQ(3, e.value());
   EXPECT_EQ(5.5f, e2.value());
   EXPECT_EQ("hello", e3.value());
@@ -154,25 +170,33 @@
   exp_string::unexpected_type unexp3 = unexpected(std::string("error"));
   exp_string e3 = unexp3;
 
+  exp_void::unexpected_type unexp4 = unexpected(10);
+  exp_void e4 = unexp4;
+
   EXPECT_FALSE(e.has_value());
   EXPECT_FALSE(e2.has_value());
   EXPECT_FALSE(e3.has_value());
+  EXPECT_FALSE(e4.has_value());
   EXPECT_EQ(10, e.error());
   EXPECT_EQ(10.5f, e2.error());
   EXPECT_EQ("error", e3.error());
+  EXPECT_EQ(10, e4.error());
 }
 
 TEST(Expected, testMoveConstructibleFromUnexpected) {
   exp_int e = unexpected(10);
   exp_double e2 = unexpected(10.5f);
   exp_string e3 = unexpected(std::string("error"));
+  exp_void e4 = unexpected(10);
 
   EXPECT_FALSE(e.has_value());
   EXPECT_FALSE(e2.has_value());
   EXPECT_FALSE(e3.has_value());
+  EXPECT_FALSE(e4.has_value());
   EXPECT_EQ(10, e.error());
   EXPECT_EQ(10.5f, e2.error());
   EXPECT_EQ("error", e3.error());
+  EXPECT_EQ(10, e4.error());
 }
 
 TEST(Expected, testConstructibleByForwarding) {
@@ -188,6 +212,9 @@
   EXPECT_TRUE(e3.has_value());
   EXPECT_EQ("hello",e3->first);
   EXPECT_EQ(30,e3->second);
+
+  exp_void e4({});
+  EXPECT_TRUE(e4.has_value());
 }
 
 TEST(Expected, testDestructible) {
@@ -217,6 +244,14 @@
 
   EXPECT_EQ(20, e3.value());
   EXPECT_EQ(20, e4.value());
+
+  exp_void e5 = unexpected(10);
+  ASSERT_FALSE(e5.has_value());
+  exp_void e6;
+  e5 = e6;
+
+  EXPECT_TRUE(e5.has_value());
+  EXPECT_TRUE(e6.has_value());
 }
 
 TEST(Expected, testAssignableFromValue) {
@@ -231,6 +266,11 @@
   exp_string e3 = "hello";
   e3 = "world";
   EXPECT_EQ("world", e3.value());
+
+  exp_void e4 = unexpected(10);
+  ASSERT_FALSE(e4.has_value());
+  e4 = {};
+  EXPECT_TRUE(e4.has_value());
 }
 
 TEST(Expected, testAssignableFromUnexpected) {
@@ -248,6 +288,11 @@
   e3 = unexpected("world");
   EXPECT_FALSE(e3.has_value());
   EXPECT_EQ("world", e3.error());
+
+  exp_void e4 = {};
+  e4 = unexpected(10);
+  EXPECT_FALSE(e4.has_value());
+  EXPECT_EQ(10, e4.error());
 }
 
 TEST(Expected, testAssignableFromMovedValue) {
@@ -285,6 +330,11 @@
   EXPECT_EQ(10.5f, t.b);
   EXPECT_EQ(3, exp.value().a);
   EXPECT_EQ(10.5, exp.value().b);
+
+  exp_void e = unexpected(10);
+  ASSERT_FALSE(e.has_value());
+  e.emplace();
+  EXPECT_TRUE(e.has_value());
 }
 
 TEST(Expected, testSwapExpectedExpected) {
@@ -296,6 +346,13 @@
   EXPECT_TRUE(e2.has_value());
   EXPECT_EQ(20, e.value());
   EXPECT_EQ(10, e2.value());
+
+  exp_void e3;
+  exp_void e4;
+  e3.swap(e4);
+
+  EXPECT_TRUE(e3.has_value());
+  EXPECT_TRUE(e4.has_value());
 }
 
 TEST(Expected, testSwapUnexpectedUnexpected) {
@@ -306,6 +363,14 @@
   EXPECT_FALSE(e2.has_value());
   EXPECT_EQ(20, e.error());
   EXPECT_EQ(10, e2.error());
+
+  exp_void e3 = unexpected(10);
+  exp_void e4 = unexpected(20);
+  e3.swap(e4);
+  EXPECT_FALSE(e3.has_value());
+  EXPECT_FALSE(e4.has_value());
+  EXPECT_EQ(20, e3.error());
+  EXPECT_EQ(10, e4.error());
 }
 
 TEST(Expected, testSwapExpectedUnepected) {
@@ -316,6 +381,13 @@
   EXPECT_TRUE(e2.has_value());
   EXPECT_EQ(30, e.error());
   EXPECT_EQ(10, e2.value());
+
+  exp_void e3;
+  exp_void e4 = unexpected(10);
+  e3.swap(e4);
+  EXPECT_FALSE(e3.has_value());
+  EXPECT_TRUE(e4.has_value());
+  EXPECT_EQ(10, e3.error());
 }
 
 TEST(Expected, testDereference) {
@@ -361,6 +433,13 @@
   EXPECT_TRUE(e2 == e);
   EXPECT_FALSE(e != e2);
   EXPECT_FALSE(e2 != e);
+
+  exp_void e3;
+  exp_void e4;
+  EXPECT_TRUE(e3 == e4);
+  EXPECT_TRUE(e4 == e3);
+  EXPECT_FALSE(e3 != e4);
+  EXPECT_FALSE(e4 != e3);
 }
 
 TEST(Expected, testDifferentValues) {
@@ -379,6 +458,13 @@
   EXPECT_FALSE(e2 == e);
   EXPECT_TRUE(e != e2);
   EXPECT_TRUE(e2 != e);
+
+  exp_void e3;
+  exp_void e4 = unexpected(10);
+  EXPECT_FALSE(e3 == e4);
+  EXPECT_FALSE(e4 == e3);
+  EXPECT_TRUE(e3 != e4);
+  EXPECT_TRUE(e4 != e3);
 }
 
 TEST(Expected, testSameErrors) {
@@ -388,6 +474,13 @@
   EXPECT_TRUE(e2 == e);
   EXPECT_FALSE(e != e2);
   EXPECT_FALSE(e2 != e);
+
+  exp_void e3 = unexpected(10);
+  exp_void e4 = unexpected(10);
+  EXPECT_TRUE(e3 == e4);
+  EXPECT_TRUE(e4 == e3);
+  EXPECT_FALSE(e3 != e4);
+  EXPECT_FALSE(e4 != e3);
 }
 
 TEST(Expected, testDifferentErrors) {
@@ -397,6 +490,13 @@
   EXPECT_FALSE(e2 == e);
   EXPECT_TRUE(e != e2);
   EXPECT_TRUE(e2 != e);
+
+  exp_void e3 = unexpected(10);
+  exp_void e4 = unexpected(20);
+  EXPECT_FALSE(e3 == e4);
+  EXPECT_FALSE(e4 == e3);
+  EXPECT_TRUE(e3 != e4);
+  EXPECT_TRUE(e4 != e3);
 }
 
 TEST(Expected, testCompareWithSameValue) {
@@ -424,6 +524,13 @@
   EXPECT_TRUE(error == e);
   EXPECT_FALSE(e != error);
   EXPECT_FALSE(error != e);
+
+  exp_void e2 = unexpected(10);
+  exp_void::unexpected_type error2 = 10;
+  EXPECT_TRUE(e2 == error2);
+  EXPECT_TRUE(error2 == e2);
+  EXPECT_FALSE(e2 != error2);
+  EXPECT_FALSE(error2 != e2);
 }
 
 TEST(Expected, testCompareWithDifferentError) {
@@ -433,6 +540,32 @@
   EXPECT_FALSE(error == e);
   EXPECT_TRUE(e != error);
   EXPECT_TRUE(error != e);
+
+  exp_void e2 = unexpected(10);
+  exp_void::unexpected_type error2 = 20;
+  EXPECT_FALSE(e2 == error2);
+  EXPECT_FALSE(error2 == e2);
+  EXPECT_TRUE(e2 != error2);
+  EXPECT_TRUE(error2 != e2);
+}
+
+TEST(Expected, testCompareDifferentType) {
+  expected<int,int> e = 10;
+  expected<int32_t, int> e2 = 10;
+  EXPECT_TRUE(e == e2);
+  e2 = 20;
+  EXPECT_FALSE(e == e2);
+
+  expected<std::string_view,int> e3 = "hello";
+  expected<std::string,int> e4 = "hello";
+  EXPECT_TRUE(e3 == e4);
+  e4 = "world";
+  EXPECT_FALSE(e3 == e4);
+
+  expected<void,int> e5;
+  expected<int,int> e6 = 10;
+  EXPECT_FALSE(e5 == e6);
+  EXPECT_FALSE(e6 == e5);
 }
 
 TEST(Expected, testDivideExample) {
@@ -478,6 +611,22 @@
   EXPECT_EQ("yes", r->first);
 }
 
+TEST(Expected, testVoid) {
+  auto test = [](bool ok) -> exp_void {
+    if (ok) {
+      return {};
+    } else {
+      return unexpected(10);
+    }
+  };
+
+  auto r = test(true);
+  EXPECT_TRUE(r);
+  r = test(false);
+  EXPECT_FALSE(r);
+  EXPECT_EQ(10, r.error());
+}
+
 // copied from result_test.cpp
 struct ConstructorTracker {
   static size_t constructor_called;
diff --git a/base/include/android-base/expected.h b/base/include/android-base/expected.h
index 2307217..08c9fb5 100644
--- a/base/include/android-base/expected.h
+++ b/base/include/android-base/expected.h
@@ -412,13 +412,7 @@
 
 template<class T1, class E1, class T2, class E2>
 constexpr bool operator!=(const expected<T1, E1>& x, const expected<T2, E2>& y) {
-  if (x.has_value() != y.has_value()) {
-    return true;
-  } else if (!x.has_value()) {
-    return x.error() != y.error();
-  } else {
-    return *x != *y;
-  }
+  return !(x == y);
 }
 
 // comparison with T
@@ -458,6 +452,194 @@
 }
 
 template<class E>
+class _NODISCARD_ expected<void, E> {
+ public:
+  using value_type = void;
+  using error_type = E;
+  using unexpected_type = unexpected<E>;
+
+  // constructors
+  constexpr expected() = default;
+  constexpr expected(const expected& rhs) = default;
+  constexpr expected(expected&& rhs) noexcept = default;
+
+  template<class U, class G _ENABLE_IF(
+    std::is_void_v<U> &&
+    std::is_convertible_v<const G&, E> /* non-explicit */
+  )>
+  constexpr expected(const expected<U, G>& rhs) {
+    if (!rhs.has_value()) var_ = unexpected(rhs.error());
+  }
+
+  template<class U, class G _ENABLE_IF(
+    std::is_void_v<U> &&
+    !std::is_convertible_v<const G&, E> /* explicit */
+  )>
+  constexpr explicit expected(const expected<U, G>& rhs) {
+    if (!rhs.has_value()) var_ = unexpected(rhs.error());
+  }
+
+  template<class U, class G _ENABLE_IF(
+    std::is_void_v<U> &&
+    std::is_convertible_v<const G&&, E> /* non-explicit */
+  )>
+  constexpr expected(expected<U, G>&& rhs) {
+    if (!rhs.has_value()) var_ = unexpected(std::move(rhs.error()));
+  }
+
+  template<class U, class G _ENABLE_IF(
+    std::is_void_v<U> &&
+    !std::is_convertible_v<const G&&, E> /* explicit */
+  )>
+  constexpr explicit expected(expected<U, G>&& rhs) {
+    if (!rhs.has_value()) var_ = unexpected(std::move(rhs.error()));
+  }
+
+  template<class G = E _ENABLE_IF(
+    std::is_constructible_v<E, const G&> &&
+    std::is_convertible_v<const G&, E> /* non-explicit */
+  )>
+  constexpr expected(const unexpected<G>& e)
+  : var_(std::in_place_index<1>, e.value()) {}
+
+  template<class G = E _ENABLE_IF(
+    std::is_constructible_v<E, const G&> &&
+    !std::is_convertible_v<const G&, E> /* explicit */
+  )>
+  constexpr explicit expected(const unexpected<G>& e)
+  : var_(std::in_place_index<1>, E(e.value())) {}
+
+  template<class G = E _ENABLE_IF(
+    std::is_constructible_v<E, G&&> &&
+    std::is_convertible_v<G&&, E> /* non-explicit */
+  )>
+  constexpr expected(unexpected<G>&& e)
+  : var_(std::in_place_index<1>, std::move(e.value())) {}
+
+  template<class G = E _ENABLE_IF(
+    std::is_constructible_v<E, G&&> &&
+    !std::is_convertible_v<G&&, E> /* explicit */
+  )>
+  constexpr explicit expected(unexpected<G>&& e)
+  : var_(std::in_place_index<1>, E(std::move(e.value()))) {}
+
+  template<class... Args _ENABLE_IF(
+    sizeof...(Args) == 0
+  )>
+  constexpr explicit expected(std::in_place_t, Args&&...) {}
+
+  template<class... Args _ENABLE_IF(
+    std::is_constructible_v<E, Args...>
+  )>
+  constexpr explicit expected(unexpect_t, Args&&... args)
+  : var_(unexpected_type(std::forward<Args>(args)...)) {}
+
+  template<class U, class... Args _ENABLE_IF(
+    std::is_constructible_v<E, std::initializer_list<U>&, Args...>
+  )>
+  constexpr explicit expected(unexpect_t, std::initializer_list<U> il, Args&&... args)
+  : var_(unexpected_type(il, std::forward<Args>(args)...)) {}
+
+  // destructor
+  ~expected() = default;
+
+  // assignment
+  // Note: SFNAIE doesn't work here because assignment operator should be
+  // non-template. We could workaround this by defining a templated parent class
+  // having the assignment operator. This incomplete implementation however
+  // doesn't allow us to copy assign expected<T,E> even when T is non-copy
+  // assignable. The copy assignment will fail by the underlying std::variant
+  // anyway though the error message won't be clear.
+  expected& operator=(const expected& rhs) = default;
+
+  // Note for SFNAIE above applies to here as well
+  expected& operator=(expected&& rhs) = default;
+
+  template<class G = E>
+  expected& operator=(const unexpected<G>& rhs) {
+    var_ = rhs;
+    return *this;
+  }
+
+  template<class G = E _ENABLE_IF(
+    std::is_nothrow_move_constructible_v<G> &&
+    std::is_move_assignable_v<G>
+  )>
+  expected& operator=(unexpected<G>&& rhs) {
+    var_ = std::move(rhs);
+    return *this;
+  }
+
+  // modifiers
+  void emplace() {
+    var_ = std::monostate();
+  }
+
+  // swap
+  template<typename = std::enable_if_t<
+    std::is_swappable_v<E>>
+  >
+  void swap(expected& rhs) noexcept(std::is_nothrow_move_constructible_v<E>) {
+    var_.swap(rhs.var_);
+  }
+
+  // observers
+  constexpr explicit operator bool() const noexcept { return has_value(); }
+  constexpr bool has_value() const noexcept { return var_.index() == 0; }
+
+  constexpr void value() const& { if (!has_value()) std::get<0>(var_); }
+
+  constexpr const E& error() const& { return std::get<unexpected_type>(var_).value(); }
+  constexpr E& error() & { return std::get<unexpected_type>(var_).value(); }
+  constexpr const E&& error() const&& { return std::move(std::get<unexpected_type>(var_)).value(); }
+  constexpr E&& error() && { return std::move(std::get<unexpected_type>(var_)).value(); }
+
+  // expected equality operators
+  template<class E1, class E2>
+  friend constexpr bool operator==(const expected<void, E1>& x, const expected<void, E2>& y);
+
+  // Specialized algorithms
+  template<class T1, class E1>
+  friend void swap(expected<T1, E1>&, expected<T1, E1>&) noexcept;
+
+ private:
+  std::variant<std::monostate, unexpected_type> var_;
+};
+
+template<class E1, class E2>
+constexpr bool operator==(const expected<void, E1>& x, const expected<void, E2>& y) {
+  if (x.has_value() != y.has_value()) {
+    return false;
+  } else if (!x.has_value()) {
+    return x.error() == y.error();
+  } else {
+    return true;
+  }
+}
+
+template<class T1, class E1, class E2>
+constexpr bool operator==(const expected<T1, E1>& x, const expected<void, E2>& y) {
+  if (x.has_value() != y.has_value()) {
+    return false;
+  } else if (!x.has_value()) {
+    return x.error() == y.error();
+  } else {
+    return false;
+  }
+}
+
+template<class E1, class T2, class E2>
+constexpr bool operator==(const expected<void, E1>& x, const expected<T2, E2>& y) {
+  if (x.has_value() != y.has_value()) {
+    return false;
+  } else if (!x.has_value()) {
+    return x.error() == y.error();
+  } else {
+    return false;
+  }
+}
+
+template<class E>
 class unexpected {
  public:
   // constructors
diff --git a/base/include/android-base/result.h b/base/include/android-base/result.h
new file mode 100644
index 0000000..8f00710
--- /dev/null
+++ b/base/include/android-base/result.h
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+
+// This file contains classes for returning a successful result along with an optional
+// arbitrarily typed return value or for returning a failure result along with an optional string
+// indicating why the function failed.
+
+// There are 3 classes that implement this functionality and one additional helper type.
+//
+// Result<T> either contains a member of type T that can be accessed using similar semantics as
+// std::optional<T> or it contains a ResultError describing an error, which can be accessed via
+// Result<T>::error().
+//
+// ResultError is a type that contains both a std::string describing the error and a copy of errno
+// from when the error occurred.  ResultError can be used in an ostream directly to print its
+// string value.
+//
+// Success is a typedef that aids in creating Result<T> that do not contain a return value.
+// Result<Success> is the correct return type for a function that either returns successfully or
+// returns an error value.  Returning Success() from a function that returns Result<Success> is the
+// correct way to indicate that a function without a return type has completed successfully.
+//
+// A successful Result<T> is constructed implicitly from any type that can be implicitly converted
+// to T or from the constructor arguments for T.  This allows you to return a type T directly from
+// a function that returns Result<T>.
+//
+// Error and ErrnoError are used to construct a Result<T> that has failed.  The Error class takes
+// an ostream as an input and are implicitly cast to a Result<T> containing that failure.
+// ErrnoError() is a helper function to create an Error class that appends ": " + strerror(errno)
+// to the end of the failure string to aid in interacting with C APIs.  Alternatively, an errno
+// value can be directly specified via the Error() constructor.
+//
+// ResultError can be used in the ostream when using Error to construct a Result<T>.  In this case,
+// the string that the ResultError takes is passed through the stream normally, but the errno is
+// passed to the Result<T>.  This can be used to pass errno from a failing C function up multiple
+// callers.
+//
+// ResultError can also directly construct a Result<T>.  This is particularly useful if you have a
+// function that return Result<T> but you have a Result<U> and want to return its error.  In this
+// case, you can return the .error() from the Result<U> to construct the Result<T>.
+
+// An example of how to use these is below:
+// Result<U> CalculateResult(const T& input) {
+//   U output;
+//   if (!SomeOtherCppFunction(input, &output)) {
+//     return Error() << "SomeOtherCppFunction(" << input << ") failed";
+//   }
+//   if (!c_api_function(output)) {
+//     return ErrnoError() << "c_api_function(" << output << ") failed";
+//   }
+//   return output;
+// }
+//
+// auto output = CalculateResult(input);
+// if (!output) return Error() << "CalculateResult failed: " << output.error();
+// UseOutput(*output);
+
+#pragma once
+
+#include <errno.h>
+
+#include <sstream>
+#include <string>
+
+#include "android-base/expected.h"
+
+namespace android {
+namespace base {
+
+struct ResultError {
+  template <typename T>
+  ResultError(T&& message, int code)
+      : message_(std::forward<T>(message)), code_(code) {}
+
+  template <typename T>
+  operator android::base::expected<T, ResultError>() {
+    return android::base::unexpected(ResultError(message_, code_));
+  }
+
+  std::string message() const { return message_; }
+  int code() const { return code_; }
+
+ private:
+  std::string message_;
+  int code_;
+};
+
+inline bool operator==(const ResultError& lhs, const ResultError& rhs) {
+  return lhs.message() == rhs.message() && lhs.code() == rhs.code();
+}
+
+inline bool operator!=(const ResultError& lhs, const ResultError& rhs) {
+  return !(lhs == rhs);
+}
+
+inline std::ostream& operator<<(std::ostream& os, const ResultError& t) {
+  os << t.message();
+  return os;
+}
+
+class Error {
+ public:
+  Error() : errno_(0), append_errno_(false) {}
+  Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
+
+  template <typename T>
+  operator android::base::expected<T, ResultError>() {
+    return android::base::unexpected(ResultError(str(), errno_));
+  }
+
+  template <typename T>
+  Error& operator<<(T&& t) {
+    int saved = errno;
+    ss_ << t;
+    errno = saved;
+    return *this;
+  }
+
+  Error& operator<<(const ResultError& result_error) {
+    (*this) << result_error.message();
+    errno_ = result_error.code();
+    return *this;
+  }
+
+  const std::string str() const {
+    std::string str = ss_.str();
+    if (append_errno_) {
+      if (str.empty()) {
+        return strerror(errno_);
+      }
+      return std::move(str) + ": " + strerror(errno_);
+    }
+    return str;
+  }
+
+  Error(const Error&) = delete;
+  Error(Error&&) = delete;
+  Error& operator=(const Error&) = delete;
+  Error& operator=(Error&&) = delete;
+
+ private:
+  std::stringstream ss_;
+  int errno_;
+  bool append_errno_;
+};
+
+inline Error ErrnoError() {
+  return Error(errno);
+}
+
+template <typename T>
+using Result = android::base::expected<T, ResultError>;
+
+// Usage: `Result<Success>` as a result type that doesn't contain a value.
+// Use `return {}` or `return Success()` to return with success.
+using Success = std::monostate;
+
+}  // namespace base
+}  // namespace android
diff --git a/base/result_test.cpp b/base/result_test.cpp
new file mode 100644
index 0000000..d31e775
--- /dev/null
+++ b/base/result_test.cpp
@@ -0,0 +1,382 @@
+/*
+ * 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.
+ */
+
+#include "android-base/result.h"
+
+#include "errno.h"
+
+#include <istream>
+#include <string>
+
+#include <gtest/gtest.h>
+
+using namespace std::string_literals;
+
+namespace android {
+namespace base {
+
+TEST(result, result_accessors) {
+  Result<std::string> result = "success";
+  ASSERT_TRUE(result);
+  ASSERT_TRUE(result.has_value());
+
+  EXPECT_EQ("success", *result);
+  EXPECT_EQ("success", result.value());
+
+  EXPECT_EQ('s', result->data()[0]);
+}
+
+TEST(result, result_accessors_rvalue) {
+  ASSERT_TRUE(Result<std::string>("success"));
+  ASSERT_TRUE(Result<std::string>("success").has_value());
+
+  EXPECT_EQ("success", *Result<std::string>("success"));
+  EXPECT_EQ("success", Result<std::string>("success").value());
+
+  EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
+}
+
+TEST(result, result_success) {
+  Result<Success> result = Success();
+  ASSERT_TRUE(result);
+  ASSERT_TRUE(result.has_value());
+
+  EXPECT_EQ(Success(), *result);
+  EXPECT_EQ(Success(), result.value());
+}
+
+TEST(result, result_success_rvalue) {
+  // Success() doesn't actually create a Result<Success> object, but rather an object that can be
+  // implicitly constructed into a Result<Success> object.
+
+  auto MakeRvalueSuccessResult = []() -> Result<Success> { return Success(); };
+  ASSERT_TRUE(MakeRvalueSuccessResult());
+  ASSERT_TRUE(MakeRvalueSuccessResult().has_value());
+
+  EXPECT_EQ(Success(), *MakeRvalueSuccessResult());
+  EXPECT_EQ(Success(), MakeRvalueSuccessResult().value());
+}
+
+TEST(result, result_void) {
+  Result<void> ok = {};
+  EXPECT_TRUE(ok);
+  ok.value();  // should not crash
+  ASSERT_DEATH(ok.error(), "");
+
+  Result<void> fail = Error() << "failure" << 1;
+  EXPECT_FALSE(fail);
+  EXPECT_EQ("failure1", fail.error().message());
+  EXPECT_EQ(0, fail.error().code());
+  EXPECT_TRUE(ok != fail);
+  ASSERT_DEATH(fail.value(), "");
+
+  auto test = [](bool ok) -> Result<void> {
+    if (ok) return {};
+    else return Error() << "failure" << 1;
+  };
+  EXPECT_TRUE(test(true));
+  EXPECT_FALSE(test(false));
+  test(true).value();  // should not crash
+  ASSERT_DEATH(test(true).error(), "");
+  ASSERT_DEATH(test(false).value(), "");
+  EXPECT_EQ("failure1", test(false).error().message());
+}
+
+TEST(result, result_error) {
+  Result<Success> result = Error() << "failure" << 1;
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  EXPECT_EQ(0, result.error().code());
+  EXPECT_EQ("failure1", result.error().message());
+}
+
+TEST(result, result_error_empty) {
+  Result<Success> result = Error();
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  EXPECT_EQ(0, result.error().code());
+  EXPECT_EQ("", result.error().message());
+}
+
+TEST(result, result_error_rvalue) {
+  // Error() and ErrnoError() aren't actually used to create a Result<T> object.
+  // Under the hood, they are an intermediate class that can be implicitly constructed into a
+  // Result<T>.  This is needed both to create the ostream and because Error() itself, by
+  // definition will not know what the type, T, of the underlying Result<T> object that it would
+  // create is.
+
+  auto MakeRvalueErrorResult = []() -> Result<Success> { return Error() << "failure" << 1; };
+  ASSERT_FALSE(MakeRvalueErrorResult());
+  ASSERT_FALSE(MakeRvalueErrorResult().has_value());
+
+  EXPECT_EQ(0, MakeRvalueErrorResult().error().code());
+  EXPECT_EQ("failure1", MakeRvalueErrorResult().error().message());
+}
+
+TEST(result, result_errno_error) {
+  constexpr int test_errno = 6;
+  errno = test_errno;
+  Result<Success> result = ErrnoError() << "failure" << 1;
+
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  EXPECT_EQ(test_errno, result.error().code());
+  EXPECT_EQ("failure1: "s + strerror(test_errno), result.error().message());
+}
+
+TEST(result, result_errno_error_no_text) {
+  constexpr int test_errno = 6;
+  errno = test_errno;
+  Result<Success> result = ErrnoError();
+
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  EXPECT_EQ(test_errno, result.error().code());
+  EXPECT_EQ(strerror(test_errno), result.error().message());
+}
+
+TEST(result, result_error_from_other_result) {
+  auto error_text = "test error"s;
+  Result<Success> result = Error() << error_text;
+
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  Result<std::string> result2 = result.error();
+
+  ASSERT_FALSE(result2);
+  ASSERT_FALSE(result2.has_value());
+
+  EXPECT_EQ(0, result.error().code());
+  EXPECT_EQ(error_text, result.error().message());
+}
+
+TEST(result, result_error_through_ostream) {
+  auto error_text = "test error"s;
+  Result<Success> result = Error() << error_text;
+
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  Result<std::string> result2 = Error() << result.error();
+
+  ASSERT_FALSE(result2);
+  ASSERT_FALSE(result2.has_value());
+
+  EXPECT_EQ(0, result.error().code());
+  EXPECT_EQ(error_text, result.error().message());
+}
+
+TEST(result, result_errno_error_through_ostream) {
+  auto error_text = "test error"s;
+  constexpr int test_errno = 6;
+  errno = 6;
+  Result<Success> result = ErrnoError() << error_text;
+
+  errno = 0;
+
+  ASSERT_FALSE(result);
+  ASSERT_FALSE(result.has_value());
+
+  Result<std::string> result2 = Error() << result.error();
+
+  ASSERT_FALSE(result2);
+  ASSERT_FALSE(result2.has_value());
+
+  EXPECT_EQ(test_errno, result.error().code());
+  EXPECT_EQ(error_text + ": " + strerror(test_errno), result.error().message());
+}
+
+TEST(result, constructor_forwarding) {
+  auto result = Result<std::string>(std::in_place, 5, 'a');
+
+  ASSERT_TRUE(result);
+  ASSERT_TRUE(result.has_value());
+
+  EXPECT_EQ("aaaaa", *result);
+}
+
+struct ConstructorTracker {
+  static size_t constructor_called;
+  static size_t copy_constructor_called;
+  static size_t move_constructor_called;
+  static size_t copy_assignment_called;
+  static size_t move_assignment_called;
+
+  template <typename T>
+  ConstructorTracker(T&& string) : string(string) {
+    ++constructor_called;
+  }
+
+  ConstructorTracker(const ConstructorTracker& ct) {
+    ++copy_constructor_called;
+    string = ct.string;
+  }
+  ConstructorTracker(ConstructorTracker&& ct) noexcept {
+    ++move_constructor_called;
+    string = std::move(ct.string);
+  }
+  ConstructorTracker& operator=(const ConstructorTracker& ct) {
+    ++copy_assignment_called;
+    string = ct.string;
+    return *this;
+  }
+  ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
+    ++move_assignment_called;
+    string = std::move(ct.string);
+    return *this;
+  }
+
+  std::string string;
+};
+
+size_t ConstructorTracker::constructor_called = 0;
+size_t ConstructorTracker::copy_constructor_called = 0;
+size_t ConstructorTracker::move_constructor_called = 0;
+size_t ConstructorTracker::copy_assignment_called = 0;
+size_t ConstructorTracker::move_assignment_called = 0;
+
+Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
+  if (in.empty()) {
+    return "literal string";
+  }
+  if (in == "test2") {
+    return ConstructorTracker(in + in + "2");
+  }
+  ConstructorTracker result(in + " " + in);
+  return result;
+};
+
+TEST(result, no_copy_on_return) {
+  // If returning parameters that may be used to implicitly construct the type T of Result<T>,
+  // then those parameters are forwarded to the construction of Result<T>.
+
+  // If returning an prvalue or xvalue, it will be move constructed during the construction of
+  // Result<T>.
+
+  // This check ensures that that is the case, and particularly that no copy constructors
+  // are called.
+
+  auto result1 = ReturnConstructorTracker("");
+  ASSERT_TRUE(result1);
+  EXPECT_EQ("literal string", result1->string);
+  EXPECT_EQ(1U, ConstructorTracker::constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
+  EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
+
+  auto result2 = ReturnConstructorTracker("test2");
+  ASSERT_TRUE(result2);
+  EXPECT_EQ("test2test22", result2->string);
+  EXPECT_EQ(2U, ConstructorTracker::constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
+  EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
+  EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
+
+  auto result3 = ReturnConstructorTracker("test3");
+  ASSERT_TRUE(result3);
+  EXPECT_EQ("test3 test3", result3->string);
+  EXPECT_EQ(3U, ConstructorTracker::constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
+  EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
+  EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
+  EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
+}
+
+// Below two tests require that we do not hide the move constructor with our forwarding reference
+// constructor.  This is done with by disabling the forwarding reference constructor if its first
+// and only type is Result<T>.
+TEST(result, result_result_with_success) {
+  auto return_result_result_with_success = []() -> Result<Result<Success>> {
+    return Result<Success>();
+  };
+  auto result = return_result_result_with_success();
+  ASSERT_TRUE(result);
+  ASSERT_TRUE(*result);
+
+  auto inner_result = result.value();
+  ASSERT_TRUE(inner_result);
+}
+
+TEST(result, result_result_with_failure) {
+  auto return_result_result_with_error = []() -> Result<Result<Success>> {
+    return Result<Success>(ResultError("failure string", 6));
+  };
+  auto result = return_result_result_with_error();
+  ASSERT_TRUE(result);
+  ASSERT_FALSE(*result);
+  EXPECT_EQ("failure string", (*result).error().message());
+  EXPECT_EQ(6, (*result).error().code());
+}
+
+// This test requires that we disable the forwarding reference constructor if Result<T> is the
+// *only* type that we are forwarding.  In otherwords, if we are forwarding Result<T>, int to
+// construct a Result<T>, then we still need the constructor.
+TEST(result, result_two_parameter_constructor_same_type) {
+  struct TestStruct {
+    TestStruct(int value) : value_(value) {}
+    TestStruct(Result<TestStruct> result, int value) : value_(result->value_ * value) {}
+    int value_;
+  };
+
+  auto return_test_struct = []() -> Result<TestStruct> {
+    return Result<TestStruct>(std::in_place, Result<TestStruct>(std::in_place, 6), 6);
+  };
+
+  auto result = return_test_struct();
+  ASSERT_TRUE(result);
+  EXPECT_EQ(36, result->value_);
+}
+
+TEST(result, die_on_access_failed_result) {
+  Result<std::string> result = Error();
+  ASSERT_DEATH(*result, "");
+}
+
+TEST(result, die_on_get_error_succesful_result) {
+  Result<std::string> result = "success";
+  ASSERT_DEATH(result.error(), "");
+}
+
+template <class CharT>
+std::basic_ostream<CharT>& SetErrnoToTwo(std::basic_ostream<CharT>& ss) {
+  errno = 2;
+  return ss;
+}
+
+TEST(result, preserve_errno) {
+  errno = 1;
+  int old_errno = errno;
+  Result<int> result = Error() << "Failed" << SetErrnoToTwo<char>;
+  ASSERT_FALSE(result);
+  EXPECT_EQ(old_errno, errno);
+
+  errno = 1;
+  old_errno = errno;
+  Result<int> result2 = ErrnoError() << "Failed" << SetErrnoToTwo<char>;
+  ASSERT_FALSE(result2);
+  EXPECT_EQ(old_errno, errno);
+  EXPECT_EQ(old_errno, result2.error().code());
+}
+
+}  // namespace base
+}  // namespace android
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 0cbdcce..b6c65da 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -714,6 +714,7 @@
                                  [&skip_mount_point](const auto& entry) {
                                      return entry.mount_point == skip_mount_point;
                                  });
+        if (it == fstab->end()) continue;
         fstab->erase(it, fstab->end());
         LOG(INFO) << "Skip mounting partition: " << skip_mount_point;
     }
diff --git a/init/Android.bp b/init/Android.bp
index eaa7fd7..fa0a35c 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -190,7 +190,6 @@
         "persistent_properties_test.cpp",
         "property_service_test.cpp",
         "property_type_test.cpp",
-        "result_test.cpp",
         "rlimit_parser_test.cpp",
         "service_test.cpp",
         "subcontext_test.cpp",
diff --git a/init/action.cpp b/init/action.cpp
index a4f6936..a40172e 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -127,7 +127,7 @@
     // report such failures unless we're running at the DEBUG log level.
     bool report_failure = !result.has_value();
     if (report_failure && android::base::GetMinimumLogSeverity() > android::base::DEBUG &&
-        result.error().as_errno == ENOENT) {
+        result.error().code() == ENOENT) {
         report_failure = false;
     }
 
@@ -139,7 +139,7 @@
 
         LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << " (" << filename_
                   << ":" << command.line() << ") took " << duration.count() << "ms and "
-                  << (result ? "succeeded" : "failed: " + result.error().as_string);
+                  << (result ? "succeeded" : "failed: " + result.error().message());
     }
 }
 
diff --git a/init/result.h b/init/result.h
index baa680d..984b257 100644
--- a/init/result.h
+++ b/init/result.h
@@ -29,8 +29,8 @@
 // string value.
 //
 // Success is a typedef that aids in creating Result<T> that do not contain a return value.
-// Result<Success> is the correct return type for a function that either returns successfully or
-// returns an error value.  Returning Success() from a function that returns Result<Success> is the
+// Result<Nothing> is the correct return type for a function that either returns successfully or
+// returns an error value.  Returning Nothing() from a function that returns Result<Nothing> is the
 // correct way to indicate that a function without a return type has completed successfully.
 //
 // A successful Result<T> is constructed implicitly from any type that can be implicitly converted
@@ -70,101 +70,10 @@
 
 #pragma once
 
-#include <errno.h>
+#include <android-base/result.h>
 
-#include <sstream>
-#include <string>
-
-#include <android-base/expected.h>
-
-namespace android {
-namespace init {
-
-struct ResultError {
-    template <typename T>
-    ResultError(T&& error_string, int error_errno)
-        : as_string(std::forward<T>(error_string)), as_errno(error_errno) {}
-
-    template <typename T>
-    operator android::base::expected<T, ResultError>() {
-        return android::base::unexpected(ResultError(as_string, as_errno));
-    }
-
-    std::string as_string;
-    int as_errno;
-};
-
-inline std::ostream& operator<<(std::ostream& os, const ResultError& t) {
-    os << t.as_string;
-    return os;
-}
-
-inline std::ostream& operator<<(std::ostream& os, ResultError&& t) {
-    os << std::move(t.as_string);
-    return os;
-}
-
-class Error {
-  public:
-    Error() : errno_(0), append_errno_(false) {}
-    Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
-
-    template <typename T>
-    operator android::base::expected<T, ResultError>() {
-        return android::base::unexpected(ResultError(str(), errno_));
-    }
-
-    template <typename T>
-    Error&& operator<<(T&& t) {
-        ss_ << std::forward<T>(t);
-        return std::move(*this);
-    }
-
-    Error&& operator<<(const ResultError& result_error) {
-        ss_ << result_error.as_string;
-        errno_ = result_error.as_errno;
-        return std::move(*this);
-    }
-
-    Error&& operator<<(ResultError&& result_error) {
-        ss_ << std::move(result_error.as_string);
-        errno_ = result_error.as_errno;
-        return std::move(*this);
-    }
-
-    const std::string str() const {
-        std::string str = ss_.str();
-        if (append_errno_) {
-            if (str.empty()) {
-                return strerror(errno_);
-            }
-            return str + ": " + strerror(errno_);
-        }
-        return str;
-    }
-
-    int get_errno() const { return errno_; }
-
-    Error(const Error&) = delete;
-    Error(Error&&) = delete;
-    Error& operator=(const Error&) = delete;
-    Error& operator=(Error&&) = delete;
-
-  private:
-    std::stringstream ss_;
-    int errno_;
-    bool append_errno_;
-};
-
-inline Error ErrnoError() {
-    return Error(errno);
-}
-
-template <typename T>
-using Result = android::base::expected<T, ResultError>;
-
-using Success = std::monostate;
-
-}  // namespace init
-}  // namespace android
-
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+using android::base::ResultError;
+using android::base::Success;
diff --git a/init/result_test.cpp b/init/result_test.cpp
deleted file mode 100644
index d3d04a0..0000000
--- a/init/result_test.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * 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.
- */
-
-#include "result.h"
-
-#include "errno.h"
-
-#include <string>
-
-#include <gtest/gtest.h>
-
-using namespace std::string_literals;
-
-namespace android {
-namespace init {
-
-TEST(result, result_accessors) {
-    Result<std::string> result = "success";
-    ASSERT_TRUE(result);
-    ASSERT_TRUE(result.has_value());
-
-    EXPECT_EQ("success", *result);
-    EXPECT_EQ("success", result.value());
-
-    EXPECT_EQ('s', result->data()[0]);
-}
-
-TEST(result, result_accessors_rvalue) {
-    ASSERT_TRUE(Result<std::string>("success"));
-    ASSERT_TRUE(Result<std::string>("success").has_value());
-
-    EXPECT_EQ("success", *Result<std::string>("success"));
-    EXPECT_EQ("success", Result<std::string>("success").value());
-
-    EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
-}
-
-TEST(result, result_success) {
-    Result<Success> result = Success();
-    ASSERT_TRUE(result);
-    ASSERT_TRUE(result.has_value());
-
-    EXPECT_EQ(Success(), *result);
-    EXPECT_EQ(Success(), result.value());
-}
-
-TEST(result, result_success_rvalue) {
-    // Success() doesn't actually create a Result<Success> object, but rather an object that can be
-    // implicitly constructed into a Result<Success> object.
-
-    auto MakeRvalueSuccessResult = []() -> Result<Success> { return Success(); };
-    ASSERT_TRUE(MakeRvalueSuccessResult());
-    ASSERT_TRUE(MakeRvalueSuccessResult().has_value());
-
-    EXPECT_EQ(Success(), *MakeRvalueSuccessResult());
-    EXPECT_EQ(Success(), MakeRvalueSuccessResult().value());
-}
-
-TEST(result, result_error) {
-    Result<Success> result = Error() << "failure" << 1;
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    EXPECT_EQ(0, result.error().as_errno);
-    EXPECT_EQ("failure1", result.error().as_string);
-}
-
-TEST(result, result_error_empty) {
-    Result<Success> result = Error();
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    EXPECT_EQ(0, result.error().as_errno);
-    EXPECT_EQ("", result.error().as_string);
-}
-
-TEST(result, result_error_rvalue) {
-    // Error() and ErrnoError() aren't actually used to create a Result<T> object.
-    // Under the hood, they are an intermediate class that can be implicitly constructed into a
-    // Result<T>.  This is needed both to create the ostream and because Error() itself, by
-    // definition will not know what the type, T, of the underlying Result<T> object that it would
-    // create is.
-
-    auto MakeRvalueErrorResult = []() -> Result<Success> { return Error() << "failure" << 1; };
-    ASSERT_FALSE(MakeRvalueErrorResult());
-    ASSERT_FALSE(MakeRvalueErrorResult().has_value());
-
-    EXPECT_EQ(0, MakeRvalueErrorResult().error().as_errno);
-    EXPECT_EQ("failure1", MakeRvalueErrorResult().error().as_string);
-}
-
-TEST(result, result_errno_error) {
-    constexpr int test_errno = 6;
-    errno = test_errno;
-    Result<Success> result = ErrnoError() << "failure" << 1;
-
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    EXPECT_EQ(test_errno, result.error().as_errno);
-    EXPECT_EQ("failure1: "s + strerror(test_errno), result.error().as_string);
-}
-
-TEST(result, result_errno_error_no_text) {
-    constexpr int test_errno = 6;
-    errno = test_errno;
-    Result<Success> result = ErrnoError();
-
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    EXPECT_EQ(test_errno, result.error().as_errno);
-    EXPECT_EQ(strerror(test_errno), result.error().as_string);
-}
-
-TEST(result, result_error_from_other_result) {
-    auto error_text = "test error"s;
-    Result<Success> result = Error() << error_text;
-
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    Result<std::string> result2 = result.error();
-
-    ASSERT_FALSE(result2);
-    ASSERT_FALSE(result2.has_value());
-
-    EXPECT_EQ(0, result.error().as_errno);
-    EXPECT_EQ(error_text, result.error().as_string);
-}
-
-TEST(result, result_error_through_ostream) {
-    auto error_text = "test error"s;
-    Result<Success> result = Error() << error_text;
-
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    Result<std::string> result2 = Error() << result.error();
-
-    ASSERT_FALSE(result2);
-    ASSERT_FALSE(result2.has_value());
-
-    EXPECT_EQ(0, result.error().as_errno);
-    EXPECT_EQ(error_text, result.error().as_string);
-}
-
-TEST(result, result_errno_error_through_ostream) {
-    auto error_text = "test error"s;
-    constexpr int test_errno = 6;
-    errno = 6;
-    Result<Success> result = ErrnoError() << error_text;
-
-    errno = 0;
-
-    ASSERT_FALSE(result);
-    ASSERT_FALSE(result.has_value());
-
-    Result<std::string> result2 = Error() << result.error();
-
-    ASSERT_FALSE(result2);
-    ASSERT_FALSE(result2.has_value());
-
-    EXPECT_EQ(test_errno, result.error().as_errno);
-    EXPECT_EQ(error_text + ": " + strerror(test_errno), result.error().as_string);
-}
-
-TEST(result, constructor_forwarding) {
-    auto result = Result<std::string>(std::in_place, 5, 'a');
-
-    ASSERT_TRUE(result);
-    ASSERT_TRUE(result.has_value());
-
-    EXPECT_EQ("aaaaa", *result);
-}
-
-struct ConstructorTracker {
-    static size_t constructor_called;
-    static size_t copy_constructor_called;
-    static size_t move_constructor_called;
-    static size_t copy_assignment_called;
-    static size_t move_assignment_called;
-
-    template <typename T>
-    ConstructorTracker(T&& string) : string(string) {
-        ++constructor_called;
-    }
-
-    ConstructorTracker(const ConstructorTracker& ct) {
-        ++copy_constructor_called;
-        string = ct.string;
-    }
-    ConstructorTracker(ConstructorTracker&& ct) noexcept {
-        ++move_constructor_called;
-        string = std::move(ct.string);
-    }
-    ConstructorTracker& operator=(const ConstructorTracker& ct) {
-        ++copy_assignment_called;
-        string = ct.string;
-        return *this;
-    }
-    ConstructorTracker& operator=(ConstructorTracker&& ct) noexcept {
-        ++move_assignment_called;
-        string = std::move(ct.string);
-        return *this;
-    }
-
-    std::string string;
-};
-
-size_t ConstructorTracker::constructor_called = 0;
-size_t ConstructorTracker::copy_constructor_called = 0;
-size_t ConstructorTracker::move_constructor_called = 0;
-size_t ConstructorTracker::copy_assignment_called = 0;
-size_t ConstructorTracker::move_assignment_called = 0;
-
-Result<ConstructorTracker> ReturnConstructorTracker(const std::string& in) {
-    if (in.empty()) {
-        return "literal string";
-    }
-    if (in == "test2") {
-        return ConstructorTracker(in + in + "2");
-    }
-    ConstructorTracker result(in + " " + in);
-    return result;
-};
-
-TEST(result, no_copy_on_return) {
-    // If returning parameters that may be used to implicitly construct the type T of Result<T>,
-    // then those parameters are forwarded to the construction of Result<T>.
-
-    // If returning an prvalue or xvalue, it will be move constructed during the construction of
-    // Result<T>.
-
-    // This check ensures that that is the case, and particularly that no copy constructors
-    // are called.
-
-    auto result1 = ReturnConstructorTracker("");
-    ASSERT_TRUE(result1);
-    EXPECT_EQ("literal string", result1->string);
-    EXPECT_EQ(1U, ConstructorTracker::constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
-    EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
-
-    auto result2 = ReturnConstructorTracker("test2");
-    ASSERT_TRUE(result2);
-    EXPECT_EQ("test2test22", result2->string);
-    EXPECT_EQ(2U, ConstructorTracker::constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
-    EXPECT_EQ(1U, ConstructorTracker::move_constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
-    EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
-
-    auto result3 = ReturnConstructorTracker("test3");
-    ASSERT_TRUE(result3);
-    EXPECT_EQ("test3 test3", result3->string);
-    EXPECT_EQ(3U, ConstructorTracker::constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
-    EXPECT_EQ(2U, ConstructorTracker::move_constructor_called);
-    EXPECT_EQ(0U, ConstructorTracker::copy_assignment_called);
-    EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
-}
-
-// Below two tests require that we do not hide the move constructor with our forwarding reference
-// constructor.  This is done with by disabling the forwarding reference constructor if its first
-// and only type is Result<T>.
-TEST(result, result_result_with_success) {
-    auto return_result_result_with_success = []() -> Result<Result<Success>> {
-        return Result<Success>();
-    };
-    auto result = return_result_result_with_success();
-    ASSERT_TRUE(result);
-    ASSERT_TRUE(*result);
-
-    auto inner_result = result.value();
-    ASSERT_TRUE(inner_result);
-}
-
-TEST(result, result_result_with_failure) {
-    auto return_result_result_with_error = []() -> Result<Result<Success>> {
-        return Result<Success>(ResultError("failure string", 6));
-    };
-    auto result = return_result_result_with_error();
-    ASSERT_TRUE(result);
-    ASSERT_FALSE(*result);
-    EXPECT_EQ("failure string", (*result).error().as_string);
-    EXPECT_EQ(6, (*result).error().as_errno);
-}
-
-// This test requires that we disable the forwarding reference constructor if Result<T> is the
-// *only* type that we are forwarding.  In otherwords, if we are forwarding Result<T>, int to
-// construct a Result<T>, then we still need the constructor.
-TEST(result, result_two_parameter_constructor_same_type) {
-    struct TestStruct {
-        TestStruct(int value) : value_(value) {}
-        TestStruct(Result<TestStruct> result, int value) : value_(result->value_ * value) {}
-        int value_;
-    };
-
-    auto return_test_struct = []() -> Result<TestStruct> {
-        return Result<TestStruct>(std::in_place, Result<TestStruct>(std::in_place, 6), 6);
-    };
-
-    auto result = return_test_struct();
-    ASSERT_TRUE(result);
-    EXPECT_EQ(36, result->value_);
-}
-
-TEST(result, die_on_access_failed_result) {
-    Result<std::string> result = Error();
-    ASSERT_DEATH(*result, "");
-}
-
-TEST(result, die_on_get_error_succesful_result) {
-    Result<std::string> result = "success";
-    ASSERT_DEATH(result.error(), "");
-}
-
-}  // namespace init
-}  // namespace android
diff --git a/init/rlimit_parser_test.cpp b/init/rlimit_parser_test.cpp
index e690bf6..6a16d3b 100644
--- a/init/rlimit_parser_test.cpp
+++ b/init/rlimit_parser_test.cpp
@@ -43,8 +43,8 @@
     auto result = ParseRlimit(input);
 
     ASSERT_FALSE(result) << "input: " << input[1];
-    EXPECT_EQ(expected_result, result.error().as_string);
-    EXPECT_EQ(0, result.error().as_errno);
+    EXPECT_EQ(expected_result, result.error().message());
+    EXPECT_EQ(0, result.error().code());
 }
 
 TEST(rlimit, RlimitSuccess) {
diff --git a/init/service.cpp b/init/service.cpp
index 8fe5b30..a54cb6b 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -1196,7 +1196,7 @@
             continue;
         }
         if (auto result = service->Start(); !result) {
-            LOG(ERROR) << result.error().as_string;
+            LOG(ERROR) << result.error().message();
         }
     }
     delayed_service_names_.clear();
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index f9eb83d..0ff479a 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -142,8 +142,8 @@
         reply->set_success(true);
     } else {
         auto* failure = reply->mutable_failure();
-        failure->set_error_string(result.error().as_string);
-        failure->set_error_errno(result.error().as_errno);
+        failure->set_error_string(result.error().message());
+        failure->set_error_errno(result.error().code());
     }
 }
 
@@ -178,7 +178,7 @@
 
         auto init_message = ReadMessage(init_fd_);
         if (!init_message) {
-            if (init_message.error().as_errno == 0) {
+            if (init_message.error().code() == 0) {
                 // If the init file descriptor was closed, let's exit quietly. If
                 // this was accidental, init will restart us. If init died, this
                 // avoids calling abort(3) unnecessarily.
diff --git a/init/subcontext_test.cpp b/init/subcontext_test.cpp
index c0662a4..2635683 100644
--- a/init/subcontext_test.cpp
+++ b/init/subcontext_test.cpp
@@ -69,7 +69,7 @@
         auto result = subcontext.Execute(std::vector<std::string>{"return_pids_as_error"});
         ASSERT_FALSE(result);
 
-        auto pids = Split(result.error().as_string, " ");
+        auto pids = Split(result.error().message(), " ");
         ASSERT_EQ(2U, pids.size());
         auto our_pid = std::to_string(getpid());
         EXPECT_NE(our_pid, pids[0]);
@@ -116,7 +116,7 @@
 
         auto result = subcontext.Execute(std::vector<std::string>{"return_words_as_error"});
         ASSERT_FALSE(result);
-        EXPECT_EQ(Join(expected_words, " "), result.error().as_string);
+        EXPECT_EQ(Join(expected_words, " "), result.error().message());
         EXPECT_EQ(first_pid, subcontext.pid());
     });
 }
@@ -130,7 +130,7 @@
 
         auto result2 = subcontext.Execute(std::vector<std::string>{"generate_sane_error"});
         ASSERT_FALSE(result2);
-        EXPECT_EQ("Sane error!", result2.error().as_string);
+        EXPECT_EQ("Sane error!", result2.error().message());
         EXPECT_NE(subcontext.pid(), first_pid);
     });
 }
@@ -139,7 +139,7 @@
     RunTest([](auto& subcontext, auto& context_string) {
         auto result = subcontext.Execute(std::vector<std::string>{"return_context_as_error"});
         ASSERT_FALSE(result);
-        ASSERT_EQ(context_string, result.error().as_string);
+        ASSERT_EQ(context_string, result.error().message());
     });
 }
 
@@ -167,7 +167,7 @@
         };
         auto result = subcontext.ExpandArgs(args);
         ASSERT_FALSE(result);
-        EXPECT_EQ("Failed to expand '" + args[1] + "'", result.error().as_string);
+        EXPECT_EQ("Failed to expand '" + args[1] + "'", result.error().message());
     });
 }
 
diff --git a/init/util_test.cpp b/init/util_test.cpp
index 8bf672c..8947256 100644
--- a/init/util_test.cpp
+++ b/init/util_test.cpp
@@ -34,7 +34,7 @@
     auto file_contents = ReadFile("/proc/does-not-exist");
     EXPECT_EQ(ENOENT, errno);
     ASSERT_FALSE(file_contents);
-    EXPECT_EQ("open() failed: No such file or directory", file_contents.error().as_string);
+    EXPECT_EQ("open() failed: No such file or directory", file_contents.error().message());
 }
 
 TEST(util, ReadFileGroupWriteable) {
@@ -45,7 +45,7 @@
     EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0620, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
     auto file_contents = ReadFile(tf.path);
     ASSERT_FALSE(file_contents) << strerror(errno);
-    EXPECT_EQ("Skipping insecure file", file_contents.error().as_string);
+    EXPECT_EQ("Skipping insecure file", file_contents.error().message());
 }
 
 TEST(util, ReadFileWorldWiteable) {
@@ -56,7 +56,7 @@
     EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0602, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
     auto file_contents = ReadFile(tf.path);
     ASSERT_FALSE(file_contents) << strerror(errno);
-    EXPECT_EQ("Skipping insecure file", file_contents.error().as_string);
+    EXPECT_EQ("Skipping insecure file", file_contents.error().message());
 }
 
 TEST(util, ReadFileSymbolicLink) {
@@ -66,7 +66,7 @@
     EXPECT_EQ(ELOOP, errno);
     ASSERT_FALSE(file_contents);
     EXPECT_EQ("open() failed: Too many symbolic links encountered",
-              file_contents.error().as_string);
+              file_contents.error().message());
 }
 
 TEST(util, ReadFileSuccess) {
@@ -131,7 +131,7 @@
 
     decoded_uid = DecodeUid("toot");
     EXPECT_FALSE(decoded_uid);
-    EXPECT_EQ("getpwnam failed: No such file or directory", decoded_uid.error().as_string);
+    EXPECT_EQ("getpwnam failed: No such file or directory", decoded_uid.error().message());
 
     decoded_uid = DecodeUid("123");
     EXPECT_TRUE(decoded_uid);
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 03177c1..21d12a1 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -559,7 +559,7 @@
 /* performance test */
 static void BM_sprintf_overhead(benchmark::State& state) {
   while (state.KeepRunning()) {
-    test_print("BM_sprintf_overhead:%zu", state.iterations());
+    test_print("BM_sprintf_overhead:%" PRIu64, state.iterations());
     state.PauseTiming();
     logd_yield();
     state.ResumeTiming();
diff --git a/logd/logd.rc b/logd/logd.rc
index 438419a..530f342 100644
--- a/logd/logd.rc
+++ b/logd/logd.rc
@@ -6,7 +6,8 @@
     file /dev/kmsg w
     user logd
     group logd system package_info readproc
-    capabilities SYSLOG AUDIT_CONTROL SETGID
+    capabilities SYSLOG AUDIT_CONTROL
+    priority 10
     writepid /dev/cpuset/system-background/tasks
 
 service logd-reinit /system/bin/logd --reinit
diff --git a/logd/main.cpp b/logd/main.cpp
index fd3cdf8..28dcc5a 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -17,6 +17,7 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <linux/capability.h>
 #include <poll.h>
 #include <sched.h>
 #include <semaphore.h>
@@ -57,35 +58,10 @@
     '<', '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) / 10, \
         '0' + LOG_MAKEPRI(LOG_DAEMON, LOG_PRI(PRI)) % 10, '>'
 
-//
-// The service is designed to be run by init, it does not respond well
-// to starting up manually. When starting up manually the sockets will
-// fail to open typically for one of the following reasons:
-//     EADDRINUSE if logger is running.
-//     EACCESS if started without precautions (below)
-//
-// Here is a cookbook procedure for starting up logd manually assuming
-// init is out of the way, pedantically all permissions and SELinux
-// security is put back in place:
-//
-//    setenforce 0
-//    rm /dev/socket/logd*
-//    chmod 777 /dev/socket
-//        # here is where you would attach the debugger or valgrind for example
-//    runcon u:r:logd:s0 /system/bin/logd </dev/null >/dev/null 2>&1 &
-//    sleep 1
-//    chmod 755 /dev/socket
-//    chown logd.logd /dev/socket/logd*
-//    restorecon /dev/socket/logd*
-//    setenforce 1
-//
-// If minimalism prevails, typical for debugging and security is not a concern:
-//
-//    setenforce 0
-//    chmod 777 /dev/socket
-//    logd
-//
-
+// The service is designed to be run by init, it does not respond well to starting up manually. Init
+// has a 'sigstop' feature that sends SIGSTOP to a service immediately before calling exec().  This
+// allows debuggers, etc to be attached to logd at the very beginning, while still having init
+// handle the user, groups, capabilities, files, etc setup.
 static int drop_privs(bool klogd, bool auditd) {
     sched_param param = {};
 
@@ -99,11 +75,6 @@
         return -1;
     }
 
-    if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
-        android::prdebug("failed to set background cgroup");
-        return -1;
-    }
-
     if (!__android_logger_property_get_bool("ro.debuggable",
                                             BOOL_DEFAULT_FALSE) &&
         prctl(PR_SET_DUMPABLE, 0) == -1) {
@@ -111,52 +82,26 @@
         return -1;
     }
 
-    std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(),
-                                                             cap_free);
-    if (cap_clear(caps.get()) < 0) return -1;
-    cap_value_t cap_value[] = { CAP_SETGID,  // must be first for below
-                                klogd ? CAP_SYSLOG : CAP_SETGID,
-                                auditd ? CAP_AUDIT_CONTROL : CAP_SETGID };
-    if (cap_set_flag(caps.get(), CAP_PERMITTED, arraysize(cap_value), cap_value,
-                     CAP_SET) < 0) {
+    std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(), cap_free);
+    if (cap_clear(caps.get()) < 0) {
         return -1;
     }
-    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, arraysize(cap_value), cap_value,
-                     CAP_SET) < 0) {
+    std::vector<cap_value_t> cap_value;
+    if (klogd) {
+        cap_value.emplace_back(CAP_SYSLOG);
+    }
+    if (auditd) {
+        cap_value.emplace_back(CAP_AUDIT_CONTROL);
+    }
+
+    if (cap_set_flag(caps.get(), CAP_PERMITTED, cap_value.size(), cap_value.data(), CAP_SET) < 0) {
+        return -1;
+    }
+    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, cap_value.size(), cap_value.data(), CAP_SET) < 0) {
         return -1;
     }
     if (cap_set_proc(caps.get()) < 0) {
-        android::prdebug(
-            "failed to set CAP_SETGID, CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)",
-            errno);
-        return -1;
-    }
-
-    gid_t groups[] = { AID_READPROC };
-
-    if (setgroups(arraysize(groups), groups) == -1) {
-        android::prdebug("failed to set AID_READPROC groups");
-        return -1;
-    }
-
-    if (setgid(AID_LOGD) != 0) {
-        android::prdebug("failed to set AID_LOGD gid");
-        return -1;
-    }
-
-    if (setuid(AID_LOGD) != 0) {
-        android::prdebug("failed to set AID_LOGD uid");
-        return -1;
-    }
-
-    if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, cap_value, CAP_CLEAR) < 0) {
-        return -1;
-    }
-    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, cap_value, CAP_CLEAR) < 0) {
-        return -1;
-    }
-    if (cap_set_proc(caps.get()) < 0) {
-        android::prdebug("failed to clear CAP_SETGID (%d)", errno);
+        android::prdebug("failed to set CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)", errno);
         return -1;
     }
 
@@ -227,30 +172,6 @@
 
 static void* reinit_thread_start(void* /*obj*/) {
     prctl(PR_SET_NAME, "logd.daemon");
-    set_sched_policy(0, SP_BACKGROUND);
-    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND);
-
-    // We should drop to AID_LOGD, if we are anything else, we have
-    // even lesser privileges and accept our fate.
-    gid_t groups[] = {
-        AID_SYSTEM,        // search access to /data/system path
-        AID_PACKAGE_INFO,  // readonly access to /data/system/packages.list
-    };
-    if (setgroups(arraysize(groups), groups) == -1) {
-        android::prdebug(
-            "logd.daemon: failed to set AID_SYSTEM AID_PACKAGE_INFO groups");
-    }
-    if (setgid(AID_LOGD) != 0) {
-        android::prdebug("logd.daemon: failed to set AID_LOGD gid");
-    }
-    if (setuid(AID_LOGD) != 0) {
-        android::prdebug("logd.daemon: failed to set AID_LOGD uid");
-    }
-
-    cap_t caps = cap_init();
-    (void)cap_clear(caps);
-    (void)cap_set_proc(caps);
-    (void)cap_free(caps);
 
     while (reinit_running && !sem_wait(&reinit) && reinit_running) {
         // uidToName Privileged Worker
@@ -373,11 +294,6 @@
 }
 
 static int issueReinit() {
-    cap_t caps = cap_init();
-    (void)cap_clear(caps);
-    (void)cap_set_proc(caps);
-    (void)cap_free(caps);
-
     int sock = TEMP_FAILURE_RETRY(socket_local_client(
         "logd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM));
     if (sock < 0) return -errno;
@@ -440,6 +356,11 @@
         if (fdPmesg < 0) android::prdebug("Failed to open %s\n", proc_kmsg);
     }
 
+    bool auditd = __android_logger_property_get_bool("ro.logd.auditd", BOOL_DEFAULT_TRUE);
+    if (drop_privs(klogd, auditd) != 0) {
+        return EXIT_FAILURE;
+    }
+
     // Reinit Thread
     sem_init(&reinit, 0, 0);
     sem_init(&uidName, 0, 0);
@@ -461,12 +382,6 @@
         pthread_attr_destroy(&attr);
     }
 
-    bool auditd =
-        __android_logger_property_get_bool("ro.logd.auditd", BOOL_DEFAULT_TRUE);
-    if (drop_privs(klogd, auditd) != 0) {
-        return EXIT_FAILURE;
-    }
-
     // Serves the purpose of managing the last logs times read on a
     // socket connection, and as a reader lock on a range of log
     // entries.
diff --git a/rootdir/etc/ld.config.legacy.txt b/rootdir/etc/ld.config.legacy.txt
index f6b5e95..ad14493 100644
--- a/rootdir/etc/ld.config.legacy.txt
+++ b/rootdir/etc/ld.config.legacy.txt
@@ -56,7 +56,7 @@
 namespace.default.link.runtime.shared_libs  = libandroidicu.so
 namespace.default.link.runtime.shared_libs += libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index 6c4f8ab..3b3f61e 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -135,7 +135,7 @@
 namespace.default.link.runtime.shared_libs  = libandroidicu.so
 namespace.default.link.runtime.shared_libs += libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
@@ -522,7 +522,7 @@
 namespace.system.links = runtime
 namespace.system.link.runtime.shared_libs  = libdexfile_external.so
 namespace.system.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.system.link.runtime.shared_libs += libicui18n.so
 namespace.system.link.runtime.shared_libs += libicuuc.so
 namespace.system.link.runtime.shared_libs += libnativebridge.so
@@ -607,7 +607,7 @@
 namespace.default.link.runtime.shared_libs  = libandroidicu.so
 namespace.default.link.runtime.shared_libs += libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
diff --git a/rootdir/etc/ld.config.vndk_lite.txt b/rootdir/etc/ld.config.vndk_lite.txt
index d616582..0880be0 100644
--- a/rootdir/etc/ld.config.vndk_lite.txt
+++ b/rootdir/etc/ld.config.vndk_lite.txt
@@ -75,7 +75,7 @@
 namespace.default.link.runtime.shared_libs  = libandroidicu.so
 namespace.default.link.runtime.shared_libs += libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
@@ -366,7 +366,7 @@
 namespace.default.links = runtime
 namespace.default.link.runtime.shared_libs  = libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
@@ -419,7 +419,7 @@
 namespace.default.link.runtime.shared_libs  = libandroidicu.so
 namespace.default.link.runtime.shared_libs += libdexfile_external.so
 namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# libicuuc.so and libicui18n.so are kept for app compat reason. http://b/130788466
+# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
 namespace.default.link.runtime.shared_libs += libicui18n.so
 namespace.default.link.runtime.shared_libs += libicuuc.so
 namespace.default.link.runtime.shared_libs += libnativebridge.so
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 84fa46e..29a0ad4 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -32,6 +32,12 @@
     # cgroup for system_server and surfaceflinger
     mkdir /dev/memcg/system 0550 system system
 
+    # set RLIMIT_NICE to allow priorities from 19 to -20
+    setrlimit nice 40 40
+
+    # Allow up to 32K FDs per process
+    setrlimit nofile 32768 32768
+
     start ueventd
 
     # Run apexd-bootstrap so that APEXes that provide critical libraries
@@ -267,12 +273,6 @@
 
     export DOWNLOAD_CACHE /data/cache
 
-    # set RLIMIT_NICE to allow priorities from 19 to -20
-    setrlimit nice 40 40
-
-    # Allow up to 32K FDs per process
-    setrlimit nofile 32768 32768
-
     # This allows the ledtrig-transient properties to be created here so
     # that they can be chown'd to system:system later on boot
     write /sys/class/leds/vibrator/trigger "transient"
diff --git a/shell_and_utilities/README.md b/shell_and_utilities/README.md
index ffda3a5..1926a4f 100644
--- a/shell_and_utilities/README.md
+++ b/shell_and_utilities/README.md
@@ -211,3 +211,32 @@
 true truncate tty tunctl ulimit umount uname uniq unix2dos unlink
 unshare uptime usleep uudecode uuencode uuidgen vconfig vmstat watch
 wc which whoami xargs xxd yes zcat
+
+## Android R
+
+BSD: grep fsck\_msdos newfs\_msdos
+
+bzip2: bzcat bzip2 bunzip2
+
+one-true-awk: awk
+
+toolbox: getevent getprop setprop start stop
+
+toybox: acpi base64 basename bc blkid blockdev cal cat chattr chcon chgrp
+chmod chown chroot chrt cksum clear cmp comm cp cpio cut date dd df
+diff dirname dmesg dos2unix du echo egrep env expand expr fallocate
+false fgrep file find flock fmt free freeramdisk fsfreeze getconf
+getenforce getfattr grep groups gunzip gzip head help hostname hwclock
+i2cdetect i2cdump i2cget i2cset iconv id ifconfig inotifyd insmod
+install ionice iorenice iotop kill killall ln load\_policy log logname
+losetup ls lsattr lsmod lsof lspci lsusb makedevs md5sum microcom
+mkdir mkfifo mknod mkswap mktemp modinfo modprobe more mount mountpoint
+mv nbd-client nc netcat netstat nice nl nohup nproc nsenter od partprobe
+paste patch pgrep pidof ping ping6 pivot\_root pkill pmap printenv
+printf prlimit ps pwd pwdx readlink realpath renice restorecon rev
+rfkill rm rmdir rmmod runcon sed sendevent seq setenforce setfattr
+setsid sha1sum sha224sum sha256sum sha384sum sha512sum sleep sort split
+stat strings stty swapoff swapon sync sysctl tac tail tar taskset tee
+time timeout top touch tr traceroute traceroute6 true truncate tty tunctl
+ulimit umount uname uniq unix2dos unlink unshare uptime usleep uudecode
+uuencode uuidgen vconfig vmstat watch wc which whoami xargs xxd yes zcat
diff --git a/toolbox/Android.bp b/toolbox/Android.bp
index 5289976..9ca5607 100644
--- a/toolbox/Android.bp
+++ b/toolbox/Android.bp
@@ -28,6 +28,8 @@
         "toolbox.c",
         "getevent.c",
         "getprop.cpp",
+        "setprop.cpp",
+        "start.cpp",
     ],
     generated_headers: [
         "toolbox_input_labels",
@@ -40,6 +42,9 @@
     symlinks: [
         "getevent",
         "getprop",
+        "setprop",
+        "start",
+        "stop",
     ],
 }
 
diff --git a/toolbox/setprop.cpp b/toolbox/setprop.cpp
new file mode 100644
index 0000000..acf8c3e
--- /dev/null
+++ b/toolbox/setprop.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2019 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 <ctype.h>
+#include <stdlib.h>
+#include <sys/system_properties.h>
+
+#include <iostream>
+
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+
+using android::base::SetProperty;
+using android::base::StartsWith;
+
+extern "C" int setprop_main(int argc, char** argv) {
+    if (argc != 3) {
+        std::cout << "usage: setprop NAME VALUE\n"
+                     "\n"
+                     "Sets an Android system property."
+                  << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    auto name = std::string{argv[1]};
+    auto value = std::string{argv[2]};
+
+    // SetProperty() doesn't tell us why it failed, and actually can't recognize most failures, so
+    // we duplicate some of init's checks here to help the user.
+
+    if (name.front() == '.' || name.back() == '.') {
+        std::cerr << "Property names must not start or end with a '.'" << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    if (name.find("..") != std::string::npos) {
+        std::cerr << "'..' is not allowed in a property name" << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    for (const auto& c : name) {
+        if (!isalnum(c) && !strchr(":@_.-", c)) {
+            std::cerr << "Invalid character '" << c << "' in name '" << name << "'" << std::endl;
+            return EXIT_FAILURE;
+        }
+    }
+
+    if (value.size() >= PROP_VALUE_MAX && !StartsWith(value, "ro.")) {
+        std::cerr << "Value '" << value << "' is too long, " << value.size()
+                  << " bytes vs a max of " << PROP_VALUE_MAX << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    if (mbstowcs(nullptr, value.data(), 0) == static_cast<std::size_t>(-1)) {
+        std::cerr << "Value '" << value << "' is not a UTF8 encoded string" << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    if (!SetProperty(name, value)) {
+        std::cerr << "Failed to set property '" << name << "' to '" << value
+                  << "'.\nSee dmesg for error reason." << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    return EXIT_SUCCESS;
+}
\ No newline at end of file
diff --git a/toolbox/start.cpp b/toolbox/start.cpp
new file mode 100644
index 0000000..b87ed15
--- /dev/null
+++ b/toolbox/start.cpp
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2019 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 <stdlib.h>
+#include <unistd.h>
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include <android-base/properties.h>
+
+using android::base::GetProperty;
+using android::base::SetProperty;
+using namespace std::literals;
+
+static void ControlService(bool start, const std::string& service) {
+    if (!android::base::SetProperty(start ? "ctl.start" : "ctl.stop", service)) {
+        std::cerr << "Unable to " << (start ? "start" : "stop") << " service '" << service
+                  << "'\nSee dmesg for error reason." << std::endl;
+        exit(EXIT_FAILURE);
+    }
+}
+
+static void ControlDefaultServices(bool start) {
+    std::vector<std::string> services = {"netd", "surfaceflinger", "zygote"};
+
+    // Only start zygote_secondary if not single arch.
+    std::string zygote_configuration = GetProperty("ro.zygote", "");
+    if (zygote_configuration != "zygote32" && zygote_configuration != "zygote64") {
+        services.emplace_back("zygote_secondary");
+    }
+
+    if (start) {
+        for (const auto& service : services) {
+            ControlService(true, service);
+        }
+    } else {
+        for (auto it = services.crbegin(); it != services.crend(); ++it) {
+            ControlService(false, *it);
+        }
+    }
+}
+
+static int StartStop(int argc, char** argv, bool start) {
+    if (getuid()) {
+        std::cerr << "Must be root" << std::endl;
+        return EXIT_FAILURE;
+    }
+
+    if (argc == 1) {
+        ControlDefaultServices(start);
+    }
+
+    if (argc == 2 && argv[1] == "--help"s) {
+        std::cout << "usage: " << (start ? "start" : "stop")
+                  << " [SERVICE...]\n"
+                     "\n"
+                  << (start ? "Starts" : "Stops")
+                  << " the given system service, or netd/surfaceflinger/zygotes." << std::endl;
+        return EXIT_SUCCESS;
+    }
+
+    for (int i = 1; i < argc; ++i) {
+        ControlService(start, argv[i]);
+    }
+    return EXIT_SUCCESS;
+}
+
+extern "C" int start_main(int argc, char** argv) {
+    return StartStop(argc, argv, true);
+}
+
+extern "C" int stop_main(int argc, char** argv) {
+    return StartStop(argc, argv, false);
+}
\ No newline at end of file
diff --git a/toolbox/tools.h b/toolbox/tools.h
index abeb3ef..9a7ebd2 100644
--- a/toolbox/tools.h
+++ b/toolbox/tools.h
@@ -1,3 +1,6 @@
 TOOL(getevent)
 TOOL(getprop)
+TOOL(setprop)
+TOOL(start)
+TOOL(stop)
 TOOL(toolbox)