Merge changes I2d005e17,If2eec162,Icfd642e6
* changes:
adb: daemon: Assign valid fd to usb_handle ep0 file descriptor
adbd: respond to device-to-host control transfers.
adbd: read, print, and ignore USB control transfers.
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 716378b..66d0c92 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -28,6 +28,13 @@
"name": "memunreachable_test"
},
{
+ "name": "memunreachable_unit_test"
+ },
+ {
+ "name": "memunreachable_unit_test",
+ "host": true
+ },
+ {
"name": "memunreachable_binder_test"
},
{
diff --git a/adb/client/commandline.cpp b/adb/client/commandline.cpp
index 728e5c1..940a416 100644
--- a/adb/client/commandline.cpp
+++ b/adb/client/commandline.cpp
@@ -1811,7 +1811,7 @@
if (argc < 2) error_exit("install-multiple requires an argument");
return install_multiple_app(argc, argv);
} else if (!strcmp(argv[0], "install-multi-package")) {
- if (argc < 3) error_exit("install-multi-package requires an argument");
+ if (argc < 2) error_exit("install-multi-package requires an argument");
return install_multi_package(argc, argv);
} else if (!strcmp(argv[0], "uninstall")) {
if (argc < 2) error_exit("uninstall requires an argument");
diff --git a/adb/daemon/include/adbd/usb.h b/adb/daemon/include/adbd/usb.h
index 3213f69..fca3c58 100644
--- a/adb/daemon/include/adbd/usb.h
+++ b/adb/daemon/include/adbd/usb.h
@@ -43,7 +43,7 @@
bool open_new_connection = true;
int (*write)(usb_handle* h, const void* data, int len);
- int (*read)(usb_handle* h, void* data, int len);
+ int (*read)(usb_handle* h, void* data, int len, bool allow_partial);
void (*kick)(usb_handle* h);
void (*close)(usb_handle* h);
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
index 4ec3ab2..1abae87 100644
--- a/adb/daemon/usb.cpp
+++ b/adb/daemon/usb.cpp
@@ -119,7 +119,7 @@
struct IoBlock {
bool pending = false;
- struct iocb control;
+ struct iocb control = {};
std::shared_ptr<Block> payload;
TransferId id() const { return TransferId::from_value(control.aio_data); }
diff --git a/adb/daemon/usb_ffs.cpp b/adb/daemon/usb_ffs.cpp
index 954e530..a64ce40 100644
--- a/adb/daemon/usb_ffs.cpp
+++ b/adb/daemon/usb_ffs.cpp
@@ -37,9 +37,12 @@
// Number of buffers needed to fit MAX_PAYLOAD, with an extra for ZLPs.
#define USB_FFS_NUM_BUFS ((4 * MAX_PAYLOAD / USB_FFS_BULK_SIZE) + 1)
+#define USB_EXT_PROP_UNICODE 1
+
#define cpu_to_le16(x) htole16(x)
#define cpu_to_le32(x) htole32(x)
+// clang-format off
struct func_desc {
struct usb_interface_descriptor intf;
struct usb_endpoint_descriptor_no_audio source;
@@ -64,6 +67,34 @@
struct func_desc fs_descs, hs_descs;
} __attribute__((packed));
+template <size_t PropertyNameLength, size_t PropertyDataLength>
+struct usb_os_desc_ext_prop {
+ uint32_t dwSize = sizeof(*this);
+ uint32_t dwPropertyDataType = cpu_to_le32(USB_EXT_PROP_UNICODE);
+
+ // Property name and value are transmitted as UTF-16, but the kernel only
+ // accepts ASCII values and performs the conversion for us.
+ uint16_t wPropertyNameLength = cpu_to_le16(PropertyNameLength);
+ char bPropertyName[PropertyNameLength];
+
+ uint32_t dwPropertyDataLength = cpu_to_le32(PropertyDataLength);
+ char bProperty[PropertyDataLength];
+} __attribute__((packed));
+
+using usb_os_desc_guid_t = usb_os_desc_ext_prop<20, 39>;
+usb_os_desc_guid_t os_desc_guid = {
+ .bPropertyName = "DeviceInterfaceGUID",
+ .bProperty = "{64379D6C-D531-4BED-BBEC-5A16FC07D6BC}",
+};
+
+struct usb_ext_prop_values {
+ usb_os_desc_guid_t guid;
+} __attribute__((packed));
+
+usb_ext_prop_values os_prop_values = {
+ .guid = os_desc_guid,
+};
+
struct desc_v2 {
struct usb_functionfs_descs_head_v2 header;
// The rest of the structure depends on the flags in the header.
@@ -75,9 +106,10 @@
struct ss_func_desc ss_descs;
struct usb_os_desc_header os_header;
struct usb_ext_compat_desc os_desc;
+ struct usb_os_desc_header os_prop_header;
+ struct usb_ext_prop_values os_prop_values;
} __attribute__((packed));
-// clang-format off
static struct func_desc fs_descriptors = {
.intf = {
.bLength = sizeof(fs_descriptors.intf),
@@ -172,13 +204,13 @@
struct usb_ext_compat_desc os_desc_compat = {
.bFirstInterfaceNumber = 0,
.Reserved1 = cpu_to_le32(1),
- .CompatibleID = {0},
+ .CompatibleID = { 'W', 'I', 'N', 'U', 'S', 'B', '\0', '\0'},
.SubCompatibleID = {0},
.Reserved2 = {0},
};
static struct usb_os_desc_header os_desc_header = {
- .interface = cpu_to_le32(1),
+ .interface = cpu_to_le32(0),
.dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)),
.bcdVersion = cpu_to_le32(1),
.wIndex = cpu_to_le32(4),
@@ -186,6 +218,14 @@
.Reserved = cpu_to_le32(0),
};
+static struct usb_os_desc_header os_prop_header = {
+ .interface = cpu_to_le32(0),
+ .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_prop_values)),
+ .bcdVersion = cpu_to_le32(1),
+ .wIndex = cpu_to_le32(5),
+ .wCount = cpu_to_le16(1),
+};
+
#define STR_INTERFACE_ "ADB Interface"
static const struct {
@@ -221,12 +261,14 @@
v2_descriptor.fs_count = 3;
v2_descriptor.hs_count = 3;
v2_descriptor.ss_count = 5;
- v2_descriptor.os_count = 1;
+ v2_descriptor.os_count = 2;
v2_descriptor.fs_descs = fs_descriptors;
v2_descriptor.hs_descs = hs_descriptors;
v2_descriptor.ss_descs = ss_descriptors;
v2_descriptor.os_header = os_desc_header;
v2_descriptor.os_desc = os_desc_compat;
+ v2_descriptor.os_prop_header = os_prop_header;
+ v2_descriptor.os_prop_values = os_prop_values;
if (out_control->get() < 0) { // might have already done this before
LOG(INFO) << "opening control endpoint " << USB_FFS_ADB_EP0;
diff --git a/adb/daemon/usb_legacy.cpp b/adb/daemon/usb_legacy.cpp
index b65727a..fe80e7d 100644
--- a/adb/daemon/usb_legacy.cpp
+++ b/adb/daemon/usb_legacy.cpp
@@ -142,11 +142,12 @@
return orig_len;
}
-static int usb_ffs_read(usb_handle* h, void* data, int len) {
+static int usb_ffs_read(usb_handle* h, void* data, int len, bool allow_partial) {
D("about to read (fd=%d, len=%d)", h->bulk_out.get(), len);
char* buf = static_cast<char*>(data);
int orig_len = len;
+ unsigned count = 0;
while (len > 0) {
int read_len = std::min(USB_FFS_BULK_SIZE, len);
int n = adb_read(h->bulk_out, buf, read_len);
@@ -156,6 +157,16 @@
}
buf += n;
len -= n;
+ count += n;
+
+ // For fastbootd command such as "getvar all", len parameter is always set 64.
+ // But what we read is actually less than 64.
+ // For example, length 10 for "getvar all" command.
+ // If we get less data than expected, this means there should be no more data.
+ if (allow_partial && n < read_len) {
+ orig_len = count;
+ break;
+ }
}
D("[ done fd=%d ]", h->bulk_out.get());
@@ -221,7 +232,7 @@
}
}
-static int usb_ffs_aio_read(usb_handle* h, void* data, int len) {
+static int usb_ffs_aio_read(usb_handle* h, void* data, int len, bool allow_partial) {
return usb_ffs_do_aio(h, data, len, true);
}
@@ -299,7 +310,7 @@
}
int usb_read(usb_handle* h, void* data, int len) {
- return h->read(h, data, len);
+ return h->read(h, data, len, false /* allow_partial */);
}
int usb_close(usb_handle* h) {
diff --git a/base/Android.bp b/base/Android.bp
index 340f814..58d3a50 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -131,6 +131,7 @@
"cmsg_test.cpp",
"endian_test.cpp",
"errors_test.cpp",
+ "expected_test.cpp",
"file_test.cpp",
"logging_test.cpp",
"macros_test.cpp",
diff --git a/base/expected_test.cpp b/base/expected_test.cpp
new file mode 100644
index 0000000..490ced4
--- /dev/null
+++ b/base/expected_test.cpp
@@ -0,0 +1,745 @@
+/*
+ * 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 "android-base/expected.h"
+
+#include <cstdio>
+#include <memory>
+#include <string>
+
+#include <gtest/gtest.h>
+
+using android::base::expected;
+using android::base::unexpected;
+
+typedef expected<int, int> exp_int;
+typedef expected<double, double> exp_double;
+typedef expected<std::string, std::string> exp_string;
+typedef expected<std::pair<std::string, int>, int> exp_pair;
+
+struct T {
+ int a;
+ int b;
+ T() = default;
+ T(int a, int b) noexcept : a(a), b(b) {}
+};
+bool operator==(const T& x, const T& y) {
+ return x.a == y.a && x.b == y.b;
+}
+bool operator!=(const T& x, const T& y) {
+ return x.a != y.a || x.b != y.b;
+}
+
+struct E {
+ std::string message;
+ int cause;
+ E(const std::string& message, int cause) : message(message), cause(cause) {}
+};
+
+typedef expected<T,E> exp_complex;
+
+TEST(Expected, testDefaultConstructible) {
+ exp_int e;
+ EXPECT_TRUE(e.has_value());
+ EXPECT_EQ(0, e.value());
+
+ exp_complex e2;
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(T(0,0), e2.value());
+}
+
+TEST(Expected, testCopyConstructible) {
+ exp_int e;
+ exp_int e2 = e;
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(0, e.value());
+ EXPECT_EQ(0, e2.value());
+}
+
+TEST(Expected, testMoveConstructible) {
+ exp_int e;
+ exp_int e2 = std::move(e);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(0, e.value());
+ EXPECT_EQ(0, e2.value());
+
+ exp_string e3(std::string("hello"));
+ exp_string e4 = std::move(e3);
+
+ EXPECT_TRUE(e3.has_value());
+ EXPECT_TRUE(e4.has_value());
+ EXPECT_EQ("", e3.value()); // e3 is moved
+ EXPECT_EQ("hello", e4.value());
+}
+
+TEST(Expected, testCopyConstructibleFromConvertibleType) {
+ exp_double e = 3.3f;
+ exp_int e2 = e;
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(3.3f, e.value());
+ EXPECT_EQ(3, e2.value());
+}
+
+TEST(Expected, testMoveConstructibleFromConvertibleType) {
+ exp_double e = 3.3f;
+ exp_int e2 = std::move(e);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(3.3f, e.value());
+ EXPECT_EQ(3, e2.value());
+}
+
+TEST(Expected, testConstructibleFromValue) {
+ exp_int e = 3;
+ exp_double e2 = 5.5f;
+ exp_string e3 = std::string("hello");
+ exp_complex e4 = T(10, 20);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_TRUE(e3.has_value());
+ EXPECT_TRUE(e4.has_value());
+ EXPECT_EQ(3, e.value());
+ EXPECT_EQ(5.5f, e2.value());
+ EXPECT_EQ("hello", e3.value());
+ EXPECT_EQ(T(10,20), e4.value());
+}
+
+TEST(Expected, testConstructibleFromMovedValue) {
+ std::string hello = "hello";
+ exp_string e = std::move(hello);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_EQ("hello", e.value());
+ EXPECT_EQ("", hello);
+}
+
+TEST(Expected, testConstructibleFromConvertibleValue) {
+ exp_int e = 3.3f; // double to int
+ exp_string e2 = "hello"; // char* to std::string
+ EXPECT_TRUE(e.has_value());
+ EXPECT_EQ(3, e.value());
+
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ("hello", e2.value());
+}
+
+TEST(Expected, testConstructibleFromUnexpected) {
+ exp_int::unexpected_type unexp = unexpected(10);
+ exp_int e = unexp;
+
+ exp_double::unexpected_type unexp2 = unexpected(10.5f);
+ exp_double e2 = unexp2;
+
+ exp_string::unexpected_type unexp3 = unexpected(std::string("error"));
+ exp_string e3 = unexp3;
+
+ EXPECT_FALSE(e.has_value());
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_FALSE(e3.has_value());
+ EXPECT_EQ(10, e.error());
+ EXPECT_EQ(10.5f, e2.error());
+ EXPECT_EQ("error", e3.error());
+}
+
+TEST(Expected, testMoveConstructibleFromUnexpected) {
+ exp_int e = unexpected(10);
+ exp_double e2 = unexpected(10.5f);
+ exp_string e3 = unexpected(std::string("error"));
+
+ EXPECT_FALSE(e.has_value());
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_FALSE(e3.has_value());
+ EXPECT_EQ(10, e.error());
+ EXPECT_EQ(10.5f, e2.error());
+ EXPECT_EQ("error", e3.error());
+}
+
+TEST(Expected, testConstructibleByForwarding) {
+ exp_string e(std::in_place, 5, 'a');
+ EXPECT_TRUE(e.has_value());
+ EXPECT_EQ("aaaaa", e.value());
+
+ exp_string e2({'a', 'b', 'c'});
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ("abc", e2.value());
+
+ exp_pair e3({"hello", 30});
+ EXPECT_TRUE(e3.has_value());
+ EXPECT_EQ("hello",e3->first);
+ EXPECT_EQ(30,e3->second);
+}
+
+TEST(Expected, testDestructible) {
+ bool destroyed = false;
+ struct T {
+ bool* flag_;
+ T(bool* flag) : flag_(flag) {}
+ ~T() { *flag_ = true; }
+ };
+ {
+ expected<T, int> exp = T(&destroyed);
+ }
+ EXPECT_TRUE(destroyed);
+}
+
+TEST(Expected, testAssignable) {
+ exp_int e = 10;
+ exp_int e2 = 20;
+ e = e2;
+
+ EXPECT_EQ(20, e.value());
+ EXPECT_EQ(20, e2.value());
+
+ exp_int e3 = 10;
+ exp_int e4 = 20;
+ e3 = std::move(e4);
+
+ EXPECT_EQ(20, e3.value());
+ EXPECT_EQ(20, e4.value());
+}
+
+TEST(Expected, testAssignableFromValue) {
+ exp_int e = 10;
+ e = 20;
+ EXPECT_EQ(20, e.value());
+
+ exp_double e2 = 3.5f;
+ e2 = 10.5f;
+ EXPECT_EQ(10.5f, e2.value());
+
+ exp_string e3 = "hello";
+ e3 = "world";
+ EXPECT_EQ("world", e3.value());
+}
+
+TEST(Expected, testAssignableFromUnexpected) {
+ exp_int e = 10;
+ e = unexpected(30);
+ EXPECT_FALSE(e.has_value());
+ EXPECT_EQ(30, e.error());
+
+ exp_double e2 = 3.5f;
+ e2 = unexpected(10.5f);
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_EQ(10.5f, e2.error());
+
+ exp_string e3 = "hello";
+ e3 = unexpected("world");
+ EXPECT_FALSE(e3.has_value());
+ EXPECT_EQ("world", e3.error());
+}
+
+TEST(Expected, testAssignableFromMovedValue) {
+ std::string world = "world";
+ exp_string e = "hello";
+ e = std::move(world);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_EQ("world", e.value());
+ EXPECT_EQ("", world);
+}
+
+TEST(Expected, testAssignableFromMovedUnexpected) {
+ std::string world = "world";
+ exp_string e = "hello";
+ e = unexpected(std::move(world));
+
+ EXPECT_FALSE(e.has_value());
+ EXPECT_EQ("world", e.error());
+ EXPECT_EQ("", world);
+}
+
+TEST(Expected, testEmplace) {
+ struct T {
+ int a;
+ double b;
+ T() {}
+ T(int a, double b) noexcept : a(a), b(b) {}
+ };
+ expected<T, int> exp;
+ T& t = exp.emplace(3, 10.5f);
+
+ EXPECT_TRUE(exp.has_value());
+ EXPECT_EQ(3, t.a);
+ EXPECT_EQ(10.5f, t.b);
+ EXPECT_EQ(3, exp.value().a);
+ EXPECT_EQ(10.5, exp.value().b);
+}
+
+TEST(Expected, testSwapExpectedExpected) {
+ exp_int e = 10;
+ exp_int e2 = 20;
+ e.swap(e2);
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(20, e.value());
+ EXPECT_EQ(10, e2.value());
+}
+
+TEST(Expected, testSwapUnexpectedUnexpected) {
+ exp_int e = unexpected(10);
+ exp_int e2 = unexpected(20);
+ e.swap(e2);
+ EXPECT_FALSE(e.has_value());
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_EQ(20, e.error());
+ EXPECT_EQ(10, e2.error());
+}
+
+TEST(Expected, testSwapExpectedUnepected) {
+ exp_int e = 10;
+ exp_int e2 = unexpected(30);
+ e.swap(e2);
+ EXPECT_FALSE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(30, e.error());
+ EXPECT_EQ(10, e2.value());
+}
+
+TEST(Expected, testDereference) {
+ struct T {
+ int a;
+ double b;
+ T() {}
+ T(int a, double b) : a(a), b(b) {}
+ };
+ expected<T, int> exp = T(3, 10.5f);
+
+ EXPECT_EQ(3, exp->a);
+ EXPECT_EQ(10.5f, exp->b);
+
+ EXPECT_EQ(3, (*exp).a);
+ EXPECT_EQ(10.5f, (*exp).b);
+}
+
+TEST(Expected, testTest) {
+ exp_int e = 10;
+ EXPECT_TRUE(e);
+ EXPECT_TRUE(e.has_value());
+
+ exp_int e2 = unexpected(10);
+ EXPECT_FALSE(e2);
+ EXPECT_FALSE(e2.has_value());
+}
+
+TEST(Expected, testGetValue) {
+ exp_int e = 10;
+ EXPECT_EQ(10, e.value());
+ EXPECT_EQ(10, e.value_or(20));
+
+ exp_int e2 = unexpected(10);
+ EXPECT_EQ(10, e2.error());
+ EXPECT_EQ(20, e2.value_or(20));
+}
+
+TEST(Expected, testSameValues) {
+ exp_int e = 10;
+ exp_int e2 = 10;
+ EXPECT_TRUE(e == e2);
+ EXPECT_TRUE(e2 == e);
+ EXPECT_FALSE(e != e2);
+ EXPECT_FALSE(e2 != e);
+}
+
+TEST(Expected, testDifferentValues) {
+ exp_int e = 10;
+ exp_int e2 = 20;
+ EXPECT_FALSE(e == e2);
+ EXPECT_FALSE(e2 == e);
+ EXPECT_TRUE(e != e2);
+ EXPECT_TRUE(e2 != e);
+}
+
+TEST(Expected, testValueWithError) {
+ exp_int e = 10;
+ exp_int e2 = unexpected(10);
+ EXPECT_FALSE(e == e2);
+ EXPECT_FALSE(e2 == e);
+ EXPECT_TRUE(e != e2);
+ EXPECT_TRUE(e2 != e);
+}
+
+TEST(Expected, testSameErrors) {
+ exp_int e = unexpected(10);
+ exp_int e2 = unexpected(10);
+ EXPECT_TRUE(e == e2);
+ EXPECT_TRUE(e2 == e);
+ EXPECT_FALSE(e != e2);
+ EXPECT_FALSE(e2 != e);
+}
+
+TEST(Expected, testDifferentErrors) {
+ exp_int e = unexpected(10);
+ exp_int e2 = unexpected(20);
+ EXPECT_FALSE(e == e2);
+ EXPECT_FALSE(e2 == e);
+ EXPECT_TRUE(e != e2);
+ EXPECT_TRUE(e2 != e);
+}
+
+TEST(Expected, testCompareWithSameValue) {
+ exp_int e = 10;
+ int value = 10;
+ EXPECT_TRUE(e == value);
+ EXPECT_TRUE(value == e);
+ EXPECT_FALSE(e != value);
+ EXPECT_FALSE(value != e);
+}
+
+TEST(Expected, testCompareWithDifferentValue) {
+ exp_int e = 10;
+ int value = 20;
+ EXPECT_FALSE(e == value);
+ EXPECT_FALSE(value == e);
+ EXPECT_TRUE(e != value);
+ EXPECT_TRUE(value != e);
+}
+
+TEST(Expected, testCompareWithSameError) {
+ exp_int e = unexpected(10);
+ exp_int::unexpected_type error = 10;
+ EXPECT_TRUE(e == error);
+ EXPECT_TRUE(error == e);
+ EXPECT_FALSE(e != error);
+ EXPECT_FALSE(error != e);
+}
+
+TEST(Expected, testCompareWithDifferentError) {
+ exp_int e = unexpected(10);
+ exp_int::unexpected_type error = 20;
+ EXPECT_FALSE(e == error);
+ EXPECT_FALSE(error == e);
+ EXPECT_TRUE(e != error);
+ EXPECT_TRUE(error != e);
+}
+
+TEST(Expected, testDivideExample) {
+ struct QR {
+ int quotient;
+ int remainder;
+ QR(int q, int r) noexcept : quotient(q), remainder(r) {}
+ bool operator==(const QR& rhs) const {
+ return quotient == rhs.quotient && remainder == rhs.remainder;
+ }
+ bool operator!=(const QR& rhs) const {
+ return quotient != rhs.quotient || remainder == rhs.remainder;
+ }
+ };
+
+ auto divide = [](int x, int y) -> expected<QR,E> {
+ if (y == 0) {
+ return unexpected(E("divide by zero", -1));
+ } else {
+ return QR(x / y, x % y);
+ }
+ };
+
+ EXPECT_FALSE(divide(10, 0));
+ EXPECT_EQ("divide by zero", divide(10, 0).error().message);
+ EXPECT_EQ(-1, divide(10, 0).error().cause);
+
+ EXPECT_TRUE(divide(10, 3));
+ EXPECT_EQ(QR(3, 1), divide(10, 3));
+}
+
+TEST(Expected, testPair) {
+ auto test = [](bool yes) -> exp_pair {
+ if (yes) {
+ return exp_pair({"yes", 42});
+ } else {
+ return unexpected(42);
+ }
+ };
+
+ auto r = test(true);
+ EXPECT_TRUE(r);
+ EXPECT_EQ("yes", r->first);
+}
+
+// copied from result_test.cpp
+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,
+ typename std::enable_if_t<std::is_convertible_v<T, std::string>>* = nullptr>
+ 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;
+ }
+ static void Reset() {
+ constructor_called = 0;
+ copy_constructor_called = 0;
+ move_constructor_called = 0;
+ copy_assignment_called = 0;
+ move_assignment_called = 0;
+ }
+ 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;
+
+typedef expected<ConstructorTracker, int> exp_track;
+
+TEST(Expected, testNumberOfCopies) {
+ // default constructor
+ ConstructorTracker::Reset();
+ exp_track e("hello");
+ 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);
+
+ // copy constructor
+ ConstructorTracker::Reset();
+ exp_track e2 = e;
+ EXPECT_EQ(0U, ConstructorTracker::constructor_called);
+ EXPECT_EQ(1U, 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);
+
+ // move constructor
+ ConstructorTracker::Reset();
+ exp_track e3 = std::move(e);
+ EXPECT_EQ(0U, 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);
+
+ // construct from lvalue
+ ConstructorTracker::Reset();
+ ConstructorTracker ct = "hello";
+ exp_track e4(ct);
+ EXPECT_EQ(1U, ConstructorTracker::constructor_called);
+ EXPECT_EQ(1U, 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);
+
+ // construct from rvalue
+ ConstructorTracker::Reset();
+ ConstructorTracker ct2 = "hello";
+ exp_track e5(std::move(ct2));
+ EXPECT_EQ(1U, 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);
+
+ // copy assignment
+ ConstructorTracker::Reset();
+ exp_track e6 = "hello";
+ exp_track e7 = "world";
+ e7 = e6;
+ EXPECT_EQ(2U, ConstructorTracker::constructor_called);
+ EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
+ EXPECT_EQ(0U, ConstructorTracker::move_constructor_called);
+ EXPECT_EQ(1U, ConstructorTracker::copy_assignment_called);
+ EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
+
+ // move assignment
+ ConstructorTracker::Reset();
+ exp_track e8 = "hello";
+ exp_track e9 = "world";
+ e9 = std::move(e8);
+ EXPECT_EQ(2U, 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(1U, ConstructorTracker::move_assignment_called);
+
+ // swap
+ ConstructorTracker::Reset();
+ exp_track e10 = "hello";
+ exp_track e11 = "world";
+ std::swap(e10, e11);
+ 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(2U, ConstructorTracker::move_assignment_called);
+}
+
+TEST(Expected, testNoCopyOnReturn) {
+ auto test = [](const std::string& in) -> exp_track {
+ if (in.empty()) {
+ return "literal string";
+ }
+ if (in == "test2") {
+ return ConstructorTracker(in + in + "2");
+ }
+ ConstructorTracker result(in + " " + in);
+ return result;
+ };
+
+ ConstructorTracker::Reset();
+ auto result1 = test("");
+ 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);
+
+ ConstructorTracker::Reset();
+ auto result2 = test("test2");
+ ASSERT_TRUE(result2);
+ EXPECT_EQ("test2test22", result2->string);
+ EXPECT_EQ(1U, 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);
+
+ ConstructorTracker::Reset();
+ auto result3 = test("test3");
+ ASSERT_TRUE(result3);
+ EXPECT_EQ("test3 test3", result3->string);
+ EXPECT_EQ(1U, 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);
+}
+
+TEST(Expected, testNested) {
+ expected<exp_string, std::string> e = "hello";
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e.value().has_value());
+ EXPECT_TRUE(e);
+ EXPECT_TRUE(*e);
+ EXPECT_EQ("hello", e.value().value());
+
+ expected<exp_string, std::string> e2 = unexpected("world");
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_FALSE(e2);
+ EXPECT_EQ("world", e2.error());
+
+ expected<exp_string, std::string> e3 = exp_string(unexpected("world"));
+ EXPECT_TRUE(e3.has_value());
+ EXPECT_FALSE(e3.value().has_value());
+ EXPECT_TRUE(e3);
+ EXPECT_FALSE(*e3);
+ EXPECT_EQ("world", e3.value().error());
+}
+
+constexpr bool equals(const char* a, const char* b) {
+ return (a == nullptr && b == nullptr) ||
+ (a != nullptr && b != nullptr && *a == *b &&
+ (*a == '\0' || equals(a + 1, b + 1)));
+}
+
+TEST(Expected, testConstexpr) {
+ // Compliation error will occur if these expressions can't be
+ // evaluated at compile time
+ constexpr exp_int e(3);
+ constexpr exp_int::unexpected_type err(3);
+ constexpr int i = 4;
+
+ // default constructor
+ static_assert(exp_int().value() == 0);
+ // copy constructor
+ static_assert(exp_int(e).value() == 3);
+ // move constructor
+ static_assert(exp_int(exp_int(4)).value() == 4);
+ // copy construct from value
+ static_assert(exp_int(i).value() == 4);
+ // copy construct from unexpected
+ static_assert(exp_int(err).error() == 3);
+ // move costruct from unexpected
+ static_assert(exp_int(unexpected(3)).error() == 3);
+ // observers
+ static_assert(*exp_int(3) == 3);
+ static_assert(exp_int(3).has_value() == true);
+ static_assert(exp_int(3).value_or(4) == 3);
+
+ typedef expected<const char*, int> exp_s;
+ constexpr exp_s s("hello");
+ constexpr const char* c = "hello";
+ static_assert(equals(exp_s().value(), nullptr));
+ static_assert(equals(exp_s(s).value(), "hello"));
+ static_assert(equals(exp_s(exp_s("hello")).value(), "hello"));
+ static_assert(equals(exp_s("hello").value(), "hello"));
+ static_assert(equals(exp_s(c).value(), "hello"));
+}
+
+TEST(Expected, testWithNonConstructible) {
+ struct AssertNotConstructed {
+ AssertNotConstructed() = delete;
+ };
+
+ expected<int, AssertNotConstructed> v(42);
+ EXPECT_TRUE(v.has_value());
+ EXPECT_EQ(42, v.value());
+
+ expected<AssertNotConstructed, int> e(unexpected(42));
+ EXPECT_FALSE(e.has_value());
+ EXPECT_EQ(42, e.error());
+}
+
+TEST(Expected, testWithMoveOnlyType) {
+ typedef expected<std::unique_ptr<int>,std::unique_ptr<int>> exp_ptr;
+ exp_ptr e(std::make_unique<int>(3));
+ exp_ptr e2(unexpected(std::make_unique<int>(4)));
+
+ EXPECT_TRUE(e.has_value());
+ EXPECT_FALSE(e2.has_value());
+ EXPECT_EQ(3, *(e.value()));
+ EXPECT_EQ(4, *(e2.error()));
+
+ e2 = std::move(e);
+ EXPECT_TRUE(e.has_value());
+ EXPECT_TRUE(e2.has_value());
+ EXPECT_EQ(3, *(e2.value()));
+}
diff --git a/base/include/android-base/expected.h b/base/include/android-base/expected.h
new file mode 100644
index 0000000..2307217
--- /dev/null
+++ b/base/include/android-base/expected.h
@@ -0,0 +1,602 @@
+/*
+ * 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 <algorithm>
+#include <initializer_list>
+#include <type_traits>
+#include <utility>
+#include <variant>
+
+// android::base::expected is an Android implementation of the std::expected
+// proposal.
+// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0323r7.html
+//
+// Usage:
+// using android::base::expected;
+// using android::base::unexpected;
+//
+// expected<double,std::string> safe_divide(double i, double j) {
+// if (j == 0) return unexpected("divide by zero");
+// else return i / j;
+// }
+//
+// void test() {
+// auto q = safe_divide(10, 0);
+// if (q) { printf("%f\n", q.value()); }
+// else { printf("%s\n", q.error().c_str()); }
+// }
+//
+// When the proposal becomes part of the standard and is implemented by
+// libcxx, this will be removed and android::base::expected will be
+// type alias to std::expected.
+//
+
+namespace android {
+namespace base {
+
+// Synopsis
+template<class T, class E>
+ class expected;
+
+template<class E>
+ class unexpected;
+template<class E>
+ unexpected(E) -> unexpected<E>;
+
+template<class E>
+ class bad_expected_access;
+
+template<>
+ class bad_expected_access<void>;
+
+struct unexpect_t {
+ explicit unexpect_t() = default;
+};
+inline constexpr unexpect_t unexpect{};
+
+// macros for SFINAE
+#define _ENABLE_IF(...) \
+ , std::enable_if_t<(__VA_ARGS__)>* = nullptr
+
+// Define NODISCARD_EXPECTED to prevent expected<T,E> from being
+// ignored when used as a return value. This is off by default.
+#ifdef NODISCARD_EXPECTED
+#define _NODISCARD_ [[nodiscard]]
+#else
+#define _NODISCARD_
+#endif
+
+namespace {
+template< class T >
+struct remove_cvref {
+ typedef std::remove_cv_t<std::remove_reference_t<T>> type;
+};
+template< class T >
+using remove_cvref_t = typename remove_cvref<T>::type;
+} // namespace
+
+// Class expected
+template<class T, class E>
+class _NODISCARD_ expected {
+ public:
+ using value_type = T;
+ using error_type = E;
+ using unexpected_type = unexpected<E>;
+
+ template<class U>
+ using rebind = expected<U, error_type>;
+
+ // 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_constructible_v<T, const U&> &&
+ std::is_constructible_v<E, const G&> &&
+ !std::is_constructible_v<T, expected<U, G>&> &&
+ !std::is_constructible_v<T, expected<U, G>&&> &&
+ !std::is_constructible_v<T, const expected<U, G>&> &&
+ !std::is_constructible_v<T, const expected<U, G>&&> &&
+ !std::is_convertible_v<expected<U, G>&, T> &&
+ !std::is_convertible_v<expected<U, G>&&, T> &&
+ !std::is_convertible_v<const expected<U, G>&, T> &&
+ !std::is_convertible_v<const expected<U, G>&&, T> &&
+ !(!std::is_convertible_v<const U&, T> ||
+ !std::is_convertible_v<const G&, E>) /* non-explicit */
+ )>
+ constexpr expected(const expected<U, G>& rhs) {
+ if (rhs.has_value()) var_ = rhs.value();
+ else var_ = unexpected(rhs.error());
+ }
+
+ template<class U, class G _ENABLE_IF(
+ std::is_constructible_v<T, const U&> &&
+ std::is_constructible_v<E, const G&> &&
+ !std::is_constructible_v<T, expected<U, G>&> &&
+ !std::is_constructible_v<T, expected<U, G>&&> &&
+ !std::is_constructible_v<T, const expected<U, G>&> &&
+ !std::is_constructible_v<T, const expected<U, G>&&> &&
+ !std::is_convertible_v<expected<U, G>&, T> &&
+ !std::is_convertible_v<expected<U, G>&&, T> &&
+ !std::is_convertible_v<const expected<U, G>&, T> &&
+ !std::is_convertible_v<const expected<U, G>&&, T> &&
+ (!std::is_convertible_v<const U&, T> ||
+ !std::is_convertible_v<const G&, E>) /* explicit */
+ )>
+ constexpr explicit expected(const expected<U, G>& rhs) {
+ if (rhs.has_value()) var_ = rhs.value();
+ else var_ = unexpected(rhs.error());
+ }
+
+ template<class U, class G _ENABLE_IF(
+ std::is_constructible_v<T, const U&> &&
+ std::is_constructible_v<E, const G&> &&
+ !std::is_constructible_v<T, expected<U, G>&> &&
+ !std::is_constructible_v<T, expected<U, G>&&> &&
+ !std::is_constructible_v<T, const expected<U, G>&> &&
+ !std::is_constructible_v<T, const expected<U, G>&&> &&
+ !std::is_convertible_v<expected<U, G>&, T> &&
+ !std::is_convertible_v<expected<U, G>&&, T> &&
+ !std::is_convertible_v<const expected<U, G>&, T> &&
+ !std::is_convertible_v<const expected<U, G>&&, T> &&
+ !(!std::is_convertible_v<const U&, T> ||
+ !std::is_convertible_v<const G&, E>) /* non-explicit */
+ )>
+ constexpr expected(expected<U, G>&& rhs) {
+ if (rhs.has_value()) var_ = std::move(rhs.value());
+ else var_ = unexpected(std::move(rhs.error()));
+ }
+
+ template<class U, class G _ENABLE_IF(
+ std::is_constructible_v<T, const U&> &&
+ std::is_constructible_v<E, const G&> &&
+ !std::is_constructible_v<T, expected<U, G>&> &&
+ !std::is_constructible_v<T, expected<U, G>&&> &&
+ !std::is_constructible_v<T, const expected<U, G>&> &&
+ !std::is_constructible_v<T, const expected<U, G>&&> &&
+ !std::is_convertible_v<expected<U, G>&, T> &&
+ !std::is_convertible_v<expected<U, G>&&, T> &&
+ !std::is_convertible_v<const expected<U, G>&, T> &&
+ !std::is_convertible_v<const expected<U, G>&&, T> &&
+ (!std::is_convertible_v<const U&, T> ||
+ !std::is_convertible_v<const G&, E>) /* explicit */
+ )>
+ constexpr explicit expected(expected<U, G>&& rhs) {
+ if (rhs.has_value()) var_ = std::move(rhs.value());
+ else var_ = unexpected(std::move(rhs.error()));
+ }
+
+ template<class U = T _ENABLE_IF(
+ std::is_constructible_v<T, U&&> &&
+ !std::is_same_v<remove_cvref_t<U>, std::in_place_t> &&
+ !std::is_same_v<expected<T, E>, remove_cvref_t<U>> &&
+ !std::is_same_v<unexpected<E>, remove_cvref_t<U>> &&
+ std::is_convertible_v<U&&,T> /* non-explicit */
+ )>
+ constexpr expected(U&& v)
+ : var_(std::in_place_index<0>, std::forward<U>(v)) {}
+
+ template<class U = T _ENABLE_IF(
+ std::is_constructible_v<T, U&&> &&
+ !std::is_same_v<remove_cvref_t<U>, std::in_place_t> &&
+ !std::is_same_v<expected<T, E>, remove_cvref_t<U>> &&
+ !std::is_same_v<unexpected<E>, remove_cvref_t<U>> &&
+ !std::is_convertible_v<U&&,T> /* explicit */
+ )>
+ constexpr explicit expected(U&& v)
+ : var_(std::in_place_index<0>, T(std::forward<U>(v))) {}
+
+ 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(
+ std::is_constructible_v<T, Args&&...>
+ )>
+ constexpr explicit expected(std::in_place_t, Args&&... args)
+ : var_(std::in_place_index<0>, std::forward<Args>(args)...) {}
+
+ template<class U, class... Args _ENABLE_IF(
+ std::is_constructible_v<T, std::initializer_list<U>&, Args...>
+ )>
+ constexpr explicit expected(std::in_place_t, std::initializer_list<U> il, Args&&... args)
+ : var_(std::in_place_index<0>, il, std::forward<Args>(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 U = T _ENABLE_IF(
+ !std::is_void_v<T> &&
+ !std::is_same_v<expected<T,E>, remove_cvref_t<U>> &&
+ !std::conjunction_v<std::is_scalar<T>, std::is_same<T, std::decay_t<U>>> &&
+ std::is_constructible_v<T,U> &&
+ std::is_assignable_v<T&,U> &&
+ std::is_nothrow_move_constructible_v<E>
+ )>
+ expected& operator=(U&& rhs) {
+ var_ = T(std::forward<U>(rhs));
+ return *this;
+ }
+
+ 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
+ template<class... Args _ENABLE_IF(
+ std::is_nothrow_constructible_v<T, Args...>
+ )>
+ T& emplace(Args&&... args) {
+ expected(std::in_place, std::forward<Args>(args)...).swap(*this);
+ return value();
+ }
+
+ template<class U, class... Args _ENABLE_IF(
+ std::is_nothrow_constructible_v<T, std::initializer_list<U>&, Args...>
+ )>
+ T& emplace(std::initializer_list<U> il, Args&&... args) {
+ expected(std::in_place, il, std::forward<Args>(args)...).swap(*this);
+ return value();
+ }
+
+ // swap
+ template<typename U = T, typename = std::enable_if_t<(
+ std::is_swappable_v<U> &&
+ std::is_swappable_v<E> &&
+ (std::is_move_constructible_v<U> ||
+ std::is_move_constructible_v<E>))>>
+ void swap(expected& rhs) noexcept(
+ std::is_nothrow_move_constructible_v<T> &&
+ std::is_nothrow_swappable_v<T> &&
+ std::is_nothrow_move_constructible_v<E> &&
+ std::is_nothrow_swappable_v<E>) {
+ var_.swap(rhs.var_);
+ }
+
+ // observers
+ constexpr const T* operator->() const { return std::addressof(value()); }
+ constexpr T* operator->() { return std::addressof(value()); }
+ constexpr const T& operator*() const& { return value(); }
+ constexpr T& operator*() & { return value(); }
+ constexpr const T&& operator*() const&& { return std::move(std::get<T>(var_)); }
+ constexpr T&& operator*() && { return std::move(std::get<T>(var_)); }
+
+ constexpr explicit operator bool() const noexcept { return has_value(); }
+ constexpr bool has_value() const noexcept { return var_.index() == 0; }
+
+ constexpr const T& value() const& { return std::get<T>(var_); }
+ constexpr T& value() & { return std::get<T>(var_); }
+ constexpr const T&& value() const&& { return std::move(std::get<T>(var_)); }
+ constexpr T&& value() && { return std::move(std::get<T>(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(); }
+
+ template<class U _ENABLE_IF(
+ std::is_copy_constructible_v<T> &&
+ std::is_convertible_v<U, T>
+ )>
+ constexpr T value_or(U&& v) const& {
+ if (has_value()) return value();
+ else return static_cast<T>(std::forward<U>(v));
+ }
+
+ template<class U _ENABLE_IF(
+ std::is_move_constructible_v<T> &&
+ std::is_convertible_v<U, T>
+ )>
+ constexpr T value_or(U&& v) && {
+ if (has_value()) return std::move(value());
+ else return static_cast<T>(std::forward<U>(v));
+ }
+
+ // expected equality operators
+ template<class T1, class E1, class T2, class E2>
+ friend constexpr bool operator==(const expected<T1, E1>& x, const expected<T2, E2>& y);
+ template<class T1, class E1, class T2, class E2>
+ friend constexpr bool operator!=(const expected<T1, E1>& x, const expected<T2, E2>& y);
+
+ // comparison with T
+ template<class T1, class E1, class T2>
+ friend constexpr bool operator==(const expected<T1, E1>&, const T2&);
+ template<class T1, class E1, class T2>
+ friend constexpr bool operator==(const T2&, const expected<T1, E1>&);
+ template<class T1, class E1, class T2>
+ friend constexpr bool operator!=(const expected<T1, E1>&, const T2&);
+ template<class T1, class E1, class T2>
+ friend constexpr bool operator!=(const T2&, const expected<T1, E1>&);
+
+ // Comparison with unexpected<E>
+ template<class T1, class E1, class E2>
+ friend constexpr bool operator==(const expected<T1, E1>&, const unexpected<E2>&);
+ template<class T1, class E1, class E2>
+ friend constexpr bool operator==(const unexpected<E2>&, const expected<T1, E1>&);
+ template<class T1, class E1, class E2>
+ friend constexpr bool operator!=(const expected<T1, E1>&, const unexpected<E2>&);
+ template<class T1, class E1, class E2>
+ friend constexpr bool operator!=(const unexpected<E2>&, const expected<T1, E1>&);
+
+ // Specialized algorithms
+ template<class T1, class E1>
+ friend void swap(expected<T1, E1>&, expected<T1, E1>&) noexcept;
+
+ private:
+ std::variant<value_type, unexpected_type> var_;
+};
+
+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 false;
+ } else if (!x.has_value()) {
+ return x.error() == y.error();
+ } else {
+ return *x == *y;
+ }
+}
+
+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;
+ }
+}
+
+// comparison with T
+template<class T1, class E1, class T2>
+constexpr bool operator==(const expected<T1, E1>& x, const T2& y) {
+ return x.has_value() && (*x == y);
+}
+template<class T1, class E1, class T2>
+constexpr bool operator==(const T2& x, const expected<T1, E1>& y) {
+ return y.has_value() && (x == *y);
+}
+template<class T1, class E1, class T2>
+constexpr bool operator!=(const expected<T1, E1>& x, const T2& y) {
+ return !x.has_value() || (*x != y);
+}
+template<class T1, class E1, class T2>
+constexpr bool operator!=(const T2& x, const expected<T1, E1>& y) {
+ return !y.has_value() || (x != *y);
+}
+
+// Comparison with unexpected<E>
+template<class T1, class E1, class E2>
+constexpr bool operator==(const expected<T1, E1>& x, const unexpected<E2>& y) {
+ return !x.has_value() && (x.error() == y.value());
+}
+template<class T1, class E1, class E2>
+constexpr bool operator==(const unexpected<E2>& x, const expected<T1, E1>& y) {
+ return !y.has_value() && (x.value() == y.error());
+}
+template<class T1, class E1, class E2>
+constexpr bool operator!=(const expected<T1, E1>& x, const unexpected<E2>& y) {
+ return x.has_value() || (x.error() != y.value());
+}
+template<class T1, class E1, class E2>
+constexpr bool operator!=(const unexpected<E2>& x, const expected<T1, E1>& y) {
+ return y.has_value() || (x.value() != y.error());
+}
+
+template<class E>
+class unexpected {
+ public:
+ // constructors
+ constexpr unexpected(const unexpected&) = default;
+ constexpr unexpected(unexpected&&) = default;
+
+ template<class Err = E _ENABLE_IF(
+ std::is_constructible_v<E, Err> &&
+ !std::is_same_v<remove_cvref_t<E>, std::in_place_t> &&
+ !std::is_same_v<remove_cvref_t<E>, unexpected>
+ )>
+ constexpr unexpected(Err&& e)
+ : val_(std::forward<Err>(e)) {}
+
+ template<class U, class... Args _ENABLE_IF(
+ std::is_constructible_v<E, std::initializer_list<U>&, Args...>
+ )>
+ constexpr explicit unexpected(std::in_place_t, std::initializer_list<U> il, Args&&... args)
+ : val_(il, std::forward<Args>(args)...) {}
+
+ template<class Err _ENABLE_IF(
+ std::is_constructible_v<E, Err> &&
+ !std::is_constructible_v<E, unexpected<Err>&> &&
+ !std::is_constructible_v<E, unexpected<Err>> &&
+ !std::is_constructible_v<E, const unexpected<Err>&> &&
+ !std::is_constructible_v<E, const unexpected<Err>> &&
+ !std::is_convertible_v<unexpected<Err>&, E> &&
+ !std::is_convertible_v<unexpected<Err>, E> &&
+ !std::is_convertible_v<const unexpected<Err>&, E> &&
+ !std::is_convertible_v<const unexpected<Err>, E> &&
+ std::is_convertible_v<Err, E> /* non-explicit */
+ )>
+ constexpr unexpected(const unexpected<Err>& rhs)
+ : val_(rhs.value()) {}
+
+ template<class Err _ENABLE_IF(
+ std::is_constructible_v<E, Err> &&
+ !std::is_constructible_v<E, unexpected<Err>&> &&
+ !std::is_constructible_v<E, unexpected<Err>> &&
+ !std::is_constructible_v<E, const unexpected<Err>&> &&
+ !std::is_constructible_v<E, const unexpected<Err>> &&
+ !std::is_convertible_v<unexpected<Err>&, E> &&
+ !std::is_convertible_v<unexpected<Err>, E> &&
+ !std::is_convertible_v<const unexpected<Err>&, E> &&
+ !std::is_convertible_v<const unexpected<Err>, E> &&
+ !std::is_convertible_v<Err, E> /* explicit */
+ )>
+ constexpr explicit unexpected(const unexpected<Err>& rhs)
+ : val_(E(rhs.value())) {}
+
+ template<class Err _ENABLE_IF(
+ std::is_constructible_v<E, Err> &&
+ !std::is_constructible_v<E, unexpected<Err>&> &&
+ !std::is_constructible_v<E, unexpected<Err>> &&
+ !std::is_constructible_v<E, const unexpected<Err>&> &&
+ !std::is_constructible_v<E, const unexpected<Err>> &&
+ !std::is_convertible_v<unexpected<Err>&, E> &&
+ !std::is_convertible_v<unexpected<Err>, E> &&
+ !std::is_convertible_v<const unexpected<Err>&, E> &&
+ !std::is_convertible_v<const unexpected<Err>, E> &&
+ std::is_convertible_v<Err, E> /* non-explicit */
+ )>
+ constexpr unexpected(unexpected<Err>&& rhs)
+ : val_(std::move(rhs.value())) {}
+
+ template<class Err _ENABLE_IF(
+ std::is_constructible_v<E, Err> &&
+ !std::is_constructible_v<E, unexpected<Err>&> &&
+ !std::is_constructible_v<E, unexpected<Err>> &&
+ !std::is_constructible_v<E, const unexpected<Err>&> &&
+ !std::is_constructible_v<E, const unexpected<Err>> &&
+ !std::is_convertible_v<unexpected<Err>&, E> &&
+ !std::is_convertible_v<unexpected<Err>, E> &&
+ !std::is_convertible_v<const unexpected<Err>&, E> &&
+ !std::is_convertible_v<const unexpected<Err>, E> &&
+ !std::is_convertible_v<Err, E> /* explicit */
+ )>
+ constexpr explicit unexpected(unexpected<Err>&& rhs)
+ : val_(E(std::move(rhs.value()))) {}
+
+ // assignment
+ constexpr unexpected& operator=(const unexpected&) = default;
+ constexpr unexpected& operator=(unexpected&&) = default;
+ template<class Err = E>
+ constexpr unexpected& operator=(const unexpected<Err>& rhs) {
+ val_ = rhs.value();
+ return *this;
+ }
+ template<class Err = E>
+ constexpr unexpected& operator=(unexpected<Err>&& rhs) {
+ val_ = std::forward<E>(rhs.value());
+ return *this;
+ }
+
+ // observer
+ constexpr const E& value() const& noexcept { return val_; }
+ constexpr E& value() & noexcept { return val_; }
+ constexpr const E&& value() const&& noexcept { return std::move(val_); }
+ constexpr E&& value() && noexcept { return std::move(val_); }
+
+ void swap(unexpected& other) noexcept(std::is_nothrow_swappable_v<E>) {
+ std::swap(val_, other.val_);
+ }
+
+ template<class E1, class E2>
+ friend constexpr bool
+ operator==(const unexpected<E1>& e1, const unexpected<E2>& e2);
+ template<class E1, class E2>
+ friend constexpr bool
+ operator!=(const unexpected<E1>& e1, const unexpected<E2>& e2);
+
+ template<class E1>
+ friend void swap(unexpected<E1>& x, unexpected<E1>& y) noexcept(noexcept(x.swap(y)));
+
+ private:
+ E val_;
+};
+
+template<class E1, class E2>
+constexpr bool
+operator==(const unexpected<E1>& e1, const unexpected<E2>& e2) {
+ return e1.value() == e2.value();
+}
+
+template<class E1, class E2>
+constexpr bool
+operator!=(const unexpected<E1>& e1, const unexpected<E2>& e2) {
+ return e1.value() != e2.value();
+}
+
+template<class E1>
+void swap(unexpected<E1>& x, unexpected<E1>& y) noexcept(noexcept(x.swap(y))) {
+ x.swap(y);
+}
+
+// TODO: bad_expected_access class
+
+#undef _ENABLE_IF
+#undef _NODISCARD_
+
+} // namespace base
+} // namespace android
diff --git a/base/mapped_file.cpp b/base/mapped_file.cpp
index f689bfa..f60de56 100644
--- a/base/mapped_file.cpp
+++ b/base/mapped_file.cpp
@@ -79,7 +79,7 @@
if (base_ != nullptr) UnmapViewOfFile(base_);
if (handle_ != nullptr) CloseHandle(handle_);
#else
- if (base_ != nullptr) munmap(base_, size_);
+ if (base_ != nullptr) munmap(base_, size_ + offset_);
#endif
base_ = nullptr;
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index c091ff7..c7be00b 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -140,7 +140,7 @@
{"mba_err", 13},
{"Watchdog", 14},
{"Panic", 15},
- {"power_key", 16},
+ {"power_key", 16}, // Mediatek
{"power_on", 17},
{"Reboot", 18},
{"rtc", 19},
@@ -203,13 +203,13 @@
{"shutdown,hibernate", 74}, // Suspend to DISK
{"power_on_key", 75},
{"reboot_by_key", 76},
- {"wdt_by_pass_pwk", 77},
+ {"wdt_by_pass_pwk", 77}, // Mediatek
{"reboot_longkey", 78},
{"powerkey", 79},
- {"usb", 80},
- {"wdt", 81},
- {"tool_by_pass_pwk", 82},
- {"2sec_reboot", 83},
+ {"usb", 80}, // Mediatek
+ {"wdt", 81}, // Mediatek
+ {"tool_by_pass_pwk", 82}, // Mediatek
+ {"2sec_reboot", 83}, // Mediatek
{"reboot,by_key", 84},
{"reboot,longkey", 85},
{"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
@@ -276,10 +276,10 @@
{"software_master", 147},
{"cold,charger", 148},
{"cold,rtc", 149},
- {"cold,rtc,2sec", 150},
- {"reboot,tool", 151},
- {"reboot,wdt", 152},
- {"reboot,unknown", 153},
+ {"cold,rtc,2sec", 150}, // Mediatek
+ {"reboot,tool", 151}, // Mediatek
+ {"reboot,wdt", 152}, // Mediatek
+ {"reboot,unknown", 153}, // Mediatek
{"kernel_panic,audit", 154},
{"kernel_panic,atomic", 155},
{"kernel_panic,hung", 156},
@@ -304,6 +304,12 @@
{"reboot,pmic_off_fault,.*", 175},
{"reboot,pmic_off_s3rst,.*", 176},
{"reboot,pmic_off_other,.*", 177},
+ {"reboot,userrequested,fastboot", 178},
+ {"reboot,userrequested,recovery", 179},
+ {"reboot,userrequested,recovery,ui", 180},
+ {"shutdown,userrequested,fastboot", 181},
+ {"shutdown,userrequested,recovery", 182},
+ {"reboot,unknown[0-9]*", 183},
};
// Converts a string value representing the reason the system booted to an
@@ -1086,17 +1092,8 @@
void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
double time_since_last_boot_sec) {
- const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
-
- if (reason.empty()) {
- android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
- end_time.count(), total_duration.count(),
- (int64_t)bootloader_duration_ms,
- (int64_t)time_since_last_boot_sec * 1000);
- return;
- }
-
- const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
+ const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "<EMPTY>");
+ const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "<EMPTY>");
android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
system_reason.c_str(), end_time.count(), total_duration.count(),
(int64_t)bootloader_duration_ms,
diff --git a/demangle/Demangler.cpp b/demangle/Demangler.cpp
index 7a3aa81..7bae356 100644
--- a/demangle/Demangler.cpp
+++ b/demangle/Demangler.cpp
@@ -15,6 +15,7 @@
*/
#include <assert.h>
+#include <string.h>
#include <cctype>
#include <stack>
diff --git a/fastboot/device/usb_client.cpp b/fastboot/device/usb_client.cpp
index 511bd5c..5066046 100644
--- a/fastboot/device/usb_client.cpp
+++ b/fastboot/device/usb_client.cpp
@@ -33,7 +33,7 @@
constexpr int kMaxPacketsizeSs = 1024;
constexpr size_t kFbFfsNumBufs = 16;
-constexpr size_t kFbFfsBufSize = 32768;
+constexpr size_t kFbFfsBufSize = 16384;
constexpr const char* kUsbFfsFastbootEp0 = "/dev/usb-ffs/fastboot/ep0";
constexpr const char* kUsbFfsFastbootOut = "/dev/usb-ffs/fastboot/ep1";
@@ -255,7 +255,8 @@
size_t bytes_read_total = 0;
while (bytes_read_total < len) {
auto bytes_to_read = std::min(len - bytes_read_total, kFbFfsNumBufs * kFbFfsBufSize);
- auto bytes_read_now = handle_->read(handle_.get(), char_data, bytes_to_read);
+ auto bytes_read_now =
+ handle_->read(handle_.get(), char_data, bytes_to_read, true /* allow_partial */);
if (bytes_read_now < 0) {
return bytes_read_total == 0 ? -1 : bytes_read_total;
}
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 25df451..39abc4a 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -1175,6 +1175,10 @@
if (!is_userspace_fastboot()) {
die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
}
+
+ // Reset target_sparse_limit after reboot to userspace fastboot. Max
+ // download sizes may differ in bootloader and fastbootd.
+ target_sparse_limit = -1;
}
class ImageSource {
diff --git a/fastboot/usb_windows.cpp b/fastboot/usb_windows.cpp
index b00edb3..bf840f8 100644
--- a/fastboot/usb_windows.cpp
+++ b/fastboot/usb_windows.cpp
@@ -195,25 +195,28 @@
ssize_t WindowsUsbTransport::Read(void* data, size_t len) {
unsigned long time_out = 0;
unsigned long read = 0;
+ size_t count = 0;
int ret;
DBG("usb_read %zu\n", len);
if (nullptr != handle_) {
- while (1) {
- int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
+ while (len > 0) {
+ size_t xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
ret = AdbReadEndpointSync(handle_->adb_read_pipe, data, xfer, &read, time_out);
errno = GetLastError();
- DBG("usb_read got: %ld, expected: %d, errno: %d\n", read, xfer, errno);
- if (ret) {
- return read;
- } else {
+ DBG("usb_read got: %lu, expected: %zu, errno: %d\n", read, xfer, errno);
+ if (ret == 0) {
// assume ERROR_INVALID_HANDLE indicates we are disconnected
if (errno == ERROR_INVALID_HANDLE)
usb_kick(handle_.get());
break;
}
- // else we timed out - try again
+ count += read;
+ len -= read;
+ data = (char*)data + read;
+
+ if (xfer != read || len == 0) return count;
}
} else {
DBG("usb_read NULL handle\n");
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index a649975..ed8cce6 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -90,7 +90,7 @@
return {};
}
-bool fs_mgr_overlayfs_setup(const char*, const char*, bool* change) {
+bool fs_mgr_overlayfs_setup(const char*, const char*, bool* change, bool) {
if (change) *change = false;
return false;
}
@@ -903,7 +903,8 @@
// Returns false if setup not permitted, errno set to last error.
// If something is altered, set *change.
-bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change) {
+bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change,
+ bool force) {
if (change) *change = false;
auto ret = false;
if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return ret;
@@ -927,7 +928,7 @@
continue;
}
save_errno = errno;
- auto verity_enabled = fs_mgr_is_verity_enabled(*it);
+ auto verity_enabled = !force && fs_mgr_is_verity_enabled(*it);
if (errno == ENOENT || errno == ENXIO) errno = save_errno;
if (verity_enabled) {
it = candidates.erase(it);
diff --git a/fs_mgr/fs_mgr_remount.cpp b/fs_mgr/fs_mgr_remount.cpp
index 6482ed3..149bee3 100644
--- a/fs_mgr/fs_mgr_remount.cpp
+++ b/fs_mgr/fs_mgr_remount.cpp
@@ -93,14 +93,14 @@
logd(id, severity, tag, file, line, message);
}
-[[noreturn]] void reboot(bool dedupe) {
- if (dedupe) {
- LOG(INFO) << "The device will now reboot to recovery and attempt un-deduplication.";
+[[noreturn]] void reboot(bool overlayfs = false) {
+ if (overlayfs) {
+ LOG(INFO) << "Successfully setup overlayfs\nrebooting device";
} else {
LOG(INFO) << "Successfully disabled verity\nrebooting device";
}
::sync();
- android::base::SetProperty(ANDROID_RB_PROPERTY, dedupe ? "reboot,recovery" : "reboot,remount");
+ android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,remount");
::sleep(60);
::exit(0); // SUCCESS
}
@@ -250,54 +250,47 @@
// Check verity and optionally setup overlayfs backing.
auto reboot_later = false;
auto user_please_reboot_later = false;
- auto uses_overlayfs = fs_mgr_overlayfs_valid() != OverlayfsValidResult::kNotSupported;
+ auto setup_overlayfs = false;
+ auto just_disabled_verity = false;
for (auto it = partitions.begin(); it != partitions.end();) {
auto& entry = *it;
auto& mount_point = entry.mount_point;
if (fs_mgr_is_verity_enabled(entry)) {
retval = VERITY_PARTITION;
+ auto ret = false;
if (android::base::GetProperty("ro.boot.vbmeta.device_state", "") != "locked") {
if (AvbOps* ops = avb_ops_user_new()) {
- auto ret = avb_user_verity_set(
+ ret = avb_user_verity_set(
ops, android::base::GetProperty("ro.boot.slot_suffix", "").c_str(),
false);
avb_ops_user_free(ops);
- if (ret) {
- LOG(WARNING) << "Disabling verity for " << mount_point;
- reboot_later = can_reboot;
- if (reboot_later) {
- // w/o overlayfs available, also check for dedupe
- if (!uses_overlayfs) {
- ++it;
- continue;
- }
- reboot(false);
- }
- user_please_reboot_later = true;
- } else if (fs_mgr_set_blk_ro(entry.blk_device, false)) {
- fec::io fh(entry.blk_device.c_str(), O_RDWR);
- if (fh && fh.set_verity_status(false)) {
- LOG(WARNING) << "Disabling verity for " << mount_point;
- reboot_later = can_reboot;
- if (reboot_later && !uses_overlayfs) {
- ++it;
- continue;
- }
- user_please_reboot_later = true;
- }
- }
+ }
+ if (!ret && fs_mgr_set_blk_ro(entry.blk_device, false)) {
+ fec::io fh(entry.blk_device.c_str(), O_RDWR);
+ ret = fh && fh.set_verity_status(false);
+ }
+ if (ret) {
+ LOG(WARNING) << "Disabling verity for " << mount_point;
+ just_disabled_verity = true;
+ reboot_later = can_reboot;
+ user_please_reboot_later = true;
}
}
- LOG(ERROR) << "Skipping " << mount_point << " for remount";
- it = partitions.erase(it);
- continue;
+ if (!ret) {
+ LOG(ERROR) << "Skipping " << mount_point << " for remount";
+ it = partitions.erase(it);
+ continue;
+ }
}
auto change = false;
errno = 0;
- if (fs_mgr_overlayfs_setup(nullptr, mount_point.c_str(), &change)) {
+ if (fs_mgr_overlayfs_setup(nullptr, mount_point.c_str(), &change, just_disabled_verity)) {
if (change) {
LOG(INFO) << "Using overlayfs for " << mount_point;
+ reboot_later = can_reboot;
+ user_please_reboot_later = true;
+ setup_overlayfs = true;
}
} else if (errno) {
PLOG(ERROR) << "Overlayfs setup for " << mount_point << " failed, skipping";
@@ -308,8 +301,8 @@
++it;
}
- if (partitions.empty()) {
- if (reboot_later) reboot(false);
+ if (partitions.empty() || just_disabled_verity) {
+ if (reboot_later) reboot(setup_overlayfs);
if (user_please_reboot_later) {
LOG(INFO) << "Now reboot your device for settings to take effect";
return 0;
@@ -389,7 +382,7 @@
retval = REMOUNT_FAILED;
}
- if (reboot_later) reboot(false);
+ if (reboot_later) reboot(setup_overlayfs);
if (user_please_reboot_later) {
LOG(INFO) << "Now reboot your device for settings to take effect";
return 0;
diff --git a/fs_mgr/include/fs_mgr_overlayfs.h b/fs_mgr/include/fs_mgr_overlayfs.h
index 6aaf1f3..9a7381f 100644
--- a/fs_mgr/include/fs_mgr_overlayfs.h
+++ b/fs_mgr/include/fs_mgr_overlayfs.h
@@ -26,7 +26,7 @@
bool fs_mgr_overlayfs_mount_all(android::fs_mgr::Fstab* fstab);
std::vector<std::string> fs_mgr_overlayfs_required_devices(android::fs_mgr::Fstab* fstab);
bool fs_mgr_overlayfs_setup(const char* backing = nullptr, const char* mount_point = nullptr,
- bool* change = nullptr);
+ bool* change = nullptr, bool force = true);
bool fs_mgr_overlayfs_teardown(const char* mount_point = nullptr, bool* change = nullptr);
bool fs_mgr_overlayfs_is_setup();
bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev);
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index c22176b..0390af3 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -33,6 +33,7 @@
## Helper Variables
##
+EMPTY=""
SPACE=" "
# A _real_ embedded tab character
TAB="`echo | tr '\n' '\t'`"
@@ -50,6 +51,9 @@
start_time=`date +%s`
ACTIVE_SLOT=
+ADB_WAIT=4m
+FASTBOOT_WAIT=2m
+
##
## Helper Functions
##
@@ -131,10 +135,30 @@
adb_logcat() {
echo "${RED}[ INFO ]${NORMAL} logcat ${@}" >&2 &&
adb logcat "${@}" </dev/null |
+ tr -d '\r' |
grep -v 'logd : logdr: UID=' |
sed -e '${/------- beginning of kernel/d}' -e 's/^[0-1][0-9]-[0-3][0-9] //'
}
+[ "USAGE: avc_check >/dev/stderr
+
+Returns: worrisome avc violations" ]
+avc_check() {
+ if ! ${overlayfs_supported:-false}; then
+ return
+ fi
+ local L=`adb_logcat -b all -v brief -d \
+ -e 'context=u:object_r:unlabeled:s0' 2>/dev/null |
+ sed -n 's/.*avc: //p' |
+ sort -u`
+ if [ -z "${L}" ]; then
+ return
+ fi
+ echo "${ORANGE}[ WARNING ]${NORMAL} unlabeled sepolicy violations:" >&2
+ echo "${L}" |
+ sed 's/^/ /' >&2
+}
+
[ "USAGE: get_property <prop>
Returns the property value" ]
@@ -173,7 +197,8 @@
Returns: true if the reboot command succeeded" ]
adb_reboot() {
- adb reboot remount-test || true
+ avc_check
+ adb reboot remount-test </dev/null || true
sleep 2
}
@@ -219,13 +244,34 @@
echo ${hours}:`expr ${minutes} / 10``expr ${minutes} % 10`:`expr ${seconds} / 10``expr ${seconds} % 10`
}
+[ "USAGE: USB_DEVICE=\`usb_devnum [--next]\`
+
+USB_DEVICE contains cache. Update if system changes.
+
+Returns: the devnum for the USB_SERIAL device" ]
+usb_devnum() {
+ if [ -n "${USB_SERIAL}" ]; then
+ local usb_device=`cat ${USB_SERIAL%/serial}/devnum 2>/dev/null | tr -d ' \t\r\n'`
+ if [ -n "${usb_device}" ]; then
+ USB_DEVICE=dev${usb_device}
+ elif [ -n "${USB_DEVICE}" -a "${1}" ]; then
+ USB_DEVICE=dev`expr ${USB_DEVICE#dev} + 1`
+ fi
+ echo "${USB_DEVICE}"
+ fi
+}
+
[ "USAGE: adb_wait [timeout]
Returns: waits until the device has returned for adb or optional timeout" ]
adb_wait() {
+ local start=`date +%s`
+ local duration=
local ret
if [ -n "${1}" ]; then
- echo -n ". . . waiting `format_duration ${1}`" ${ANDROID_SERIAL} ${USB_ADDRESS} "${CR}"
+ USB_DEVICE=`usb_devnum --next`
+ duration=`format_duration ${1}`
+ echo -n ". . . waiting ${duration}" ${ANDROID_SERIAL} ${USB_ADDRESS} ${USB_DEVICE} "${CR}"
timeout --preserve-status --signal=KILL ${1} adb wait-for-device 2>/dev/null
ret=${?}
echo -n " ${CR}"
@@ -233,30 +279,83 @@
adb wait-for-device
ret=${?}
fi
+ USB_DEVICE=`usb_devnum`
if [ 0 = ${ret} -a -n "${ACTIVE_SLOT}" ]; then
local active_slot=`get_active_slot`
if [ X"${ACTIVE_SLOT}" != X"${active_slot}" ]; then
echo "${ORANGE}[ WARNING ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}" >&2
fi
fi
+ local end=`date +%s`
+ local diff_time=`expr ${end} - ${start}`
+ local _print_time=${print_time}
+ if [ ${diff_time} -lt 15 ]; then
+ _print_time=false
+ fi
+ diff_time=`format_duration ${diff_time}`
+ if [ "${diff_time}" = "${duration}" ]; then
+ _print_time=false
+ fi
+
+ local reason=
+ if inAdb; then
+ reason=`get_property ro.boot.bootreason`
+ fi
+ case ${reason} in
+ reboot*)
+ reason=
+ ;;
+ ${EMPTY})
+ ;;
+ *)
+ reason=" for boot reason ${reason}"
+ ;;
+ esac
+ if ${_print_time} || [ -n "${reason}" ]; then
+ echo "${BLUE}[ INFO ]${NORMAL} adb wait duration ${diff_time}${reason}"
+ fi >&2
+
return ${ret}
}
-[ "USAGE: usb_status > stdout
+[ "USAGE: adb_user > /dev/stdout
-If adb_wait failed, check if device is in adb, recovery or fastboot mode
-and report status string.
+Returns: the adb daemon user" ]
+adb_user() {
+ adb_sh echo '${USER}' </dev/null
+}
-Returns: \"(USB stack borken?)\", \"(In fastboot mode)\" or \"(in adb mode)\"" ]
+[ "USAGE: usb_status > stdout 2> stderr
+
+Assumes referenced right after adb_wait or fastboot_wait failued.
+If wait failed, check if device is in adb, recovery or fastboot mode
+and report status strings like \"(USB stack borken?)\",
+\"(In fastboot mode)\", \"(In recovery mode)\" or \"(in adb mode)\".
+Additional diagnostics may be provided to the stderr output.
+
+Returns: USB status string" ]
usb_status() {
if inFastboot; then
echo "(In fastboot mode)"
elif inRecovery; then
echo "(In recovery mode)"
elif inAdb; then
- echo "(In adb mode)"
+ echo "(In adb mode `adb_user`)"
else
- echo "(USB stack borken?)"
+ echo "(USB stack borken for ${USB_ADDRESS})"
+ USB_DEVICE=`usb_devnum`
+ if [ -n "${USB_DEVICE}" ]; then
+ echo "# lsusb -v -s ${USB_DEVICE#dev}"
+ local D=`lsusb -v -s ${USB_DEVICE#dev} 2>&1`
+ if [ -n "${D}" ]; then
+ echo "${D}"
+ else
+ lsusb -v
+ fi
+ else
+ echo "# lsusb -v (expected device missing)"
+ lsusb -v
+ fi >&2
fi
}
@@ -268,7 +367,8 @@
# fastboot has no wait-for-device, but it does an automatic
# wait and requires (even a nonsensical) command to do so.
if [ -n "${1}" ]; then
- echo -n ". . . waiting `format_duration ${1}`" ${ANDROID_SERIAL} ${USB_ADDRESS} "${CR}"
+ USB_DEVICE=`usb_devnum --next`
+ echo -n ". . . waiting `format_duration ${1}`" ${ANDROID_SERIAL} ${USB_ADDRESS} ${USB_DEVICE} "${CR}"
timeout --preserve-status --signal=KILL ${1} fastboot wait-for-device >/dev/null 2>/dev/null
ret=${?}
echo -n " ${CR}"
@@ -278,11 +378,12 @@
fi ||
inFastboot
ret=${?}
+ USB_DEVICE=`usb_devnum`
if [ 0 = ${ret} -a -n "${ACTIVE_SLOT}" ]; then
local active_slot=`get_active_slot`
if [ X"${ACTIVE_SLOT}" != X"${active_slot}" ]; then
- echo "${ORANGE}[ WARNING ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}" >&2
- fi
+ echo "${ORANGE}[ WARNING ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}"
+ fi >&2
fi
return ${ret}
}
@@ -293,7 +394,8 @@
recovery_wait() {
local ret
if [ -n "${1}" ]; then
- echo -n ". . . waiting `format_duration ${1}`" ${ANDROID_SERIAL} ${USB_ADDRESS} "${CR}"
+ USB_DEVICE=`usb_devnum --next`
+ echo -n ". . . waiting `format_duration ${1}`" ${ANDROID_SERIAL} ${USB_ADDRESS} ${USB_DEVICE} "${CR}"
timeout --preserve-status --signal=KILL ${1} adb wait-for-recovery 2>/dev/null
ret=${?}
echo -n " ${CR}"
@@ -301,11 +403,12 @@
adb wait-for-recovery
ret=${?}
fi
+ USB_DEVICE=`usb_devnum`
if [ 0 = ${ret} -a -n "${ACTIVE_SLOT}" ]; then
local active_slot=`get_active_slot`
if [ X"${ACTIVE_SLOT}" != X"${active_slot}" ]; then
- echo "${ORANGE}[ WARNING ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}" >&2
- fi
+ echo "${ORANGE}[ WARNING ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}"
+ fi >&2
fi
return ${ret}
}
@@ -327,17 +430,68 @@
inFastboot || inAdb || inRecovery
}
+wait_for_screen_timeout=900
+[ "USAGE: wait_for_screen [-n] [TIMEOUT]
+
+-n - echo newline at exit
+TIMEOUT - default `format_duration ${wait_for_screen_timeout}`" ]
+wait_for_screen() {
+ exit_function=true
+ if [ X"-n" = X"${1}" ]; then
+ exit_function=echo
+ shift
+ fi
+ timeout=${wait_for_screen_timeout}
+ if [ ${#} -gt 0 ]; then
+ timeout=${1}
+ shift
+ fi
+ counter=0
+ while true; do
+ if inFastboot; then
+ fastboot reboot
+ elif inAdb; then
+ if [ 0 != ${counter} ]; then
+ adb_wait
+ fi
+ if [ -n "`get_property sys.boot.reason`" ]
+ then
+ vals=`get_property |
+ sed -n 's/[[]sys[.]\(boot_completed\|logbootcomplete\)[]]: [[]\([01]\)[]]$/\1=\2/p'`
+ if [ "${vals}" = "`echo boot_completed=1 ; echo logbootcomplete=1`" ]
+ then
+ sleep 1
+ break
+ fi
+ if [ "${vals}" = "`echo logbootcomplete=1 ; echo boot_completed=1`" ]
+ then
+ sleep 1
+ break
+ fi
+ fi
+ fi
+ counter=`expr ${counter} + 1`
+ if [ ${counter} -gt ${timeout} ]; then
+ ${exit_function}
+ echo "ERROR: wait_for_screen() timed out (`format_duration ${timeout}`)" >&2
+ return 1
+ fi
+ sleep 1
+ done
+ ${exit_function}
+}
+
[ "USAGE: adb_root
NB: This can be flakey on devices due to USB state
Returns: true if device in root state" ]
adb_root() {
- [ root != "`adb_sh echo '${USER}' </dev/null`" ] || return 0
+ [ root != "`adb_user`" ] || return 0
adb root >/dev/null </dev/null 2>/dev/null
sleep 2
- adb_wait 2m &&
- [ root = "`adb_sh echo '${USER}' </dev/null`" ]
+ adb_wait ${ADB_WAIT} &&
+ [ root = "`adb_user`" ]
}
[ "USAGE: adb_unroot
@@ -346,11 +500,11 @@
Returns: true if device in un root state" ]
adb_unroot() {
- [ root = "`adb_sh echo '${USER}' </dev/null`" ] || return 0
+ [ root = "`adb_user`" ] || return 0
adb unroot >/dev/null </dev/null 2>/dev/null
sleep 2
- adb_wait 2m &&
- [ root != "`adb_sh echo '${USER}' </dev/null`" ]
+ adb_wait ${ADB_WAIT} &&
+ [ root != "`adb_user`" ]
}
[ "USAGE: fastboot_getvar var expected >/dev/stderr
@@ -370,10 +524,10 @@
O="${1}: <empty>"
fi
if [ -n "${2}" -a "${1}: ${2}" != "${O}" ]; then
- echo "${2} != ${O}" >&2
+ echo "${2} != ${O}"
false
return
- fi
+ fi >&2
echo ${O} >&2
}
@@ -430,16 +584,16 @@
Returns: exit failure, report status" ]
die() {
if [ X"-d" = X"${1}" ]; then
- adb_logcat -b all -v nsec -d >&2
+ adb_logcat -b all -v nsec -d
shift
elif [ X"-t" = X"${1}" ]; then
if [ -n "${2}" ]; then
- adb_logcat -b all -v nsec -t ${2} >&2
+ adb_logcat -b all -v nsec -t ${2}
else
- adb_logcat -b all -v nsec -d >&2
+ adb_logcat -b all -v nsec -d
fi
shift 2
- fi
+ fi >&2
echo "${RED}[ FAILED ]${NORMAL} ${@}" >&2
cleanup
restore
@@ -464,39 +618,63 @@
if ! ( echo X"${rval}" | grep '^X'"${lval}"'$' >/dev/null 2>/dev/null ); then
if [ `echo ${lval}${rval}${*} | wc -c` -gt 50 -o "${rval}" != "${rval%
*}" ]; then
- echo "${prefix} expected \"${lval}\"" >&2
+ echo "${prefix} expected \"${lval}\""
echo "${prefix} got \"${rval}\"" |
sed ': again
N
s/\(\n\)\([^ ]\)/\1 \2/
- t again' >&2
+ t again'
if [ -n "${*}" ] ; then
- echo "${prefix} ${*}" >&2
+ echo "${prefix} ${*}"
fi
else
- echo "${prefix} expected \"${lval}\" got \"${rval}\" ${*}" >&2
- fi
+ echo "${prefix} expected \"${lval}\" got \"${rval}\" ${*}"
+ fi >&2
return ${error}
fi
if [ -n "${*}" ] ; then
prefix="${GREEN}[ INFO ]${NORMAL}"
if [ X"${lval}" != X"${rval}" ]; then # we were supplied a regex?
if [ `echo ${lval}${rval}${*} | wc -c` -gt 60 -o "${rval}" != "${rval% *}" ]; then
- echo "${prefix} ok \"${lval}\"" >&2
+ echo "${prefix} ok \"${lval}\""
echo " = \"${rval}\"" |
sed ': again
N
s/\(\n\)\([^ ]\)/\1 \2/
- t again' >&2
+ t again'
if [ -n "${*}" ] ; then
- echo "${prefix} ${*}" >&2
+ echo "${prefix} ${*}"
fi
else
- echo "${prefix} ok \"${lval}\" = \"${rval}\" ${*}" >&2
+ echo "${prefix} ok \"${lval}\" = \"${rval}\" ${*}"
fi
else
- echo "${prefix} ok \"${lval}\" ${*}" >&2
- fi
+ echo "${prefix} ok \"${lval}\" ${*}"
+ fi >&2
+ fi
+ return 0
+}
+
+[ "USAGE: EXPECT_NE <lval> <rval> [--warning [message]]
+
+Returns true if lval matches rval" ]
+EXPECT_NE() {
+ local lval="${1}"
+ local rval="${2}"
+ shift 2
+ local error=1
+ local prefix="${RED}[ ERROR ]${NORMAL}"
+ if [ X"${1}" = X"--warning" ]; then
+ prefix="${RED}[ WARNING ]${NORMAL}"
+ error=0
+ shift 1
+ fi
+ if [ X"${rval}" = X"${lval}" ]; then
+ echo "${prefix} did not expect \"${lval}\" ${*}" >&2
+ return ${error}
+ fi
+ if [ -n "${*}" ] ; then
+ echo "${prefix} ok \"${lval}\" not \"${rval}\" ${*}" >&2
fi
return 0
}
@@ -516,6 +694,21 @@
die "${@}"
}
+[ "USAGE: check_ne <lval> <rval> [--warning [message]]
+
+Exits if lval matches rval" ]
+check_ne() {
+ local lval="${1}"
+ local rval="${2}"
+ shift 2
+ if [ X"${1}" = X"--warning" ]; then
+ EXPECT_NE "${lval}" "${rval}" ${*}
+ return
+ fi
+ EXPECT_NE "${lval}" "${rval}" ||
+ die "${@}"
+}
+
[ "USAGE: skip_administrative_mounts [data] < /proc/mounts
Filters out all administrative (eg: sysfs) mounts uninteresting to the test" ]
@@ -606,7 +799,7 @@
inRecovery && die "device in recovery mode"
if ! inAdb; then
echo "${ORANGE}[ WARNING ]${NORMAL} device not in adb mode" >&2
- adb_wait 2m
+ adb_wait ${ADB_WAIT}
fi
inAdb || die "specified device not in adb mode"
isDebuggable || die "device not a debug build"
@@ -631,7 +824,8 @@
USB_ADDRESS=usb${USB_ADDRESS##*/}
fi
[ -z "${ANDROID_SERIAL}${USB_ADDRESS}" ] ||
- echo "${BLUE}[ INFO ]${NORMAL}" ${ANDROID_SERIAL} ${USB_ADDRESS} >&2
+ USB_DEVICE=`usb_devnum`
+ echo "${BLUE}[ INFO ]${NORMAL}" ${ANDROID_SERIAL} ${USB_ADDRESS} ${USB_DEVICE} >&2
BUILD_DESCRIPTION=`get_property ro.build.description`
[ -z "${BUILD_DESCRIPTION}" ] ||
echo "${BLUE}[ INFO ]${NORMAL} ${BUILD_DESCRIPTION}" >&2
@@ -657,6 +851,8 @@
esac
done
+# If reboot too soon after fresh flash, could trip device update failure logic
+wait_for_screen
# Can we test remount -R command?
overlayfs_supported=true
if [ "orange" = "`get_property ro.boot.verifiedbootstate`" -a \
@@ -665,19 +861,20 @@
${overlayfs_supported} || return 0
inFastboot &&
fastboot reboot &&
- adb_wait 2m
+ adb_wait ${ADB_WAIT}
inAdb &&
adb_root &&
adb enable-verity >/dev/null 2>/dev/null &&
adb_reboot &&
- adb_wait 2m
+ adb_wait ${ADB_WAIT}
}
echo "${GREEN}[ RUN ]${NORMAL} Testing adb shell su root remount -R command" >&2
+ avc_check
adb_su remount -R system </dev/null || true
sleep 2
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
die "waiting for device after remount -R `usb_status`"
if [ "orange" != "`get_property ro.boot.verifiedbootstate`" -o \
"2" = "`get_property partition.system.verified`" ]; then
@@ -735,7 +932,7 @@
if ${reboot}; then
echo "${ORANGE}[ WARNING ]${NORMAL} rebooting before test" >&2
adb_reboot &&
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
die "lost device after reboot after wipe `usb_status`"
adb_root ||
die "lost device after elevation to root after wipe `usb_status`"
@@ -766,6 +963,15 @@
echo "${D}"
if [ X"${D}" = X"${D##* 100[%] }" ] && ${no_dedupe} ; then
overlayfs_needed=false
+ # if device does not need overlays, then adb enable-verity will brick device
+ restore() {
+ ${overlayfs_supported} || return 0
+ inFastboot &&
+ fastboot reboot &&
+ adb_wait ${ADB_WAIT}
+ inAdb &&
+ adb_wait ${ADB_WAIT}
+ }
elif ! ${overlayfs_supported}; then
die "need overlayfs, but do not have it"
fi
@@ -800,7 +1006,7 @@
echo "${GREEN}[ INFO ]${NORMAL} rebooting as requested" >&2
L=`adb_logcat -b all -v nsec -t ${T} 2>&1`
adb_reboot &&
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
die "lost device after reboot requested `usb_status`"
adb_root ||
die "lost device after elevation to root `usb_status`"
@@ -841,6 +1047,11 @@
echo "${GREEN}[ RUN ]${NORMAL} remount" >&2
+# Feed log with selinux denials as baseline before overlays
+adb_unroot
+adb_sh find /system /vendor </dev/null >/dev/null 2>/dev/null
+adb_root
+
D=`adb remount 2>&1`
ret=${?}
echo "${D}"
@@ -941,6 +1152,26 @@
B="`adb_cat /vendor/hello`" ||
die "vendor hello"
check_eq "${A}" "${B}" /vendor before reboot
+SYSTEM_DEVT=`adb_sh stat --format=%D /system/hello </dev/null`
+VENDOR_DEVT=`adb_sh stat --format=%D /vendor/hello </dev/null`
+SYSTEM_INO=`adb_sh stat --format=%i /system/hello </dev/null`
+VENDOR_INO=`adb_sh stat --format=%i /vendor/hello </dev/null`
+BASE_SYSTEM_DEVT=`adb_sh stat --format=%D /system/bin/stat </dev/null`
+BASE_VENDOR_DEVT=`adb_sh stat --format=%D /vendor/bin/stat </dev/null`
+check_eq "${SYSTEM_DEVT%[0-9a-fA-F][0-9a-fA-F]}" "${VENDOR_DEVT%[0-9a-fA-F][0-9a-fA-F]}" vendor and system devt
+check_ne "${SYSTEM_INO}" "${VENDOR_INO}" vendor and system inode
+if ${overlayfs_needed}; then
+ check_ne "${SYSTEM_DEVT}" "${BASE_SYSTEM_DEVT}" system devt
+ check_ne "${VENDOR_DEVT}" "${BASE_VENDOR_DEVT}" vendor devt
+else
+ check_eq "${SYSTEM_DEVT}" "${BASE_SYSTEM_DEVT}" system devt
+ check_eq "${VENDOR_DEVT}" "${BASE_VENDOR_DEVT}" vendor devt
+fi
+check_ne "${BASE_SYSTEM_DEVT}" "${BASE_VENDOR_DEVT}" --warning system/vendor devt
+[ -n "${SYSTEM_DEVT%[0-9a-fA-F][0-9a-fA-F]}" ] ||
+ die "system devt ${SYSTEM_DEVT} is major 0"
+[ -n "${VENDOR_DEVT%[0-9a-fA-F][0-9a-fA-F]}" ] ||
+ die "vendor devt ${SYSTEM_DEVT} is major 0"
# Download libc.so, append some gargage, push back, and check if the file
# is updated.
@@ -961,8 +1192,16 @@
echo "${GREEN}[ RUN ]${NORMAL} reboot to confirm content persistent" >&2
+fixup_from_recovery() {
+ inRecovery || return 1
+ echo "${ORANGE}[ ERROR ]${NORMAL} Device in recovery" >&2
+ adb reboot </dev/null
+ adb_wait ${ADB_WAIT}
+}
+
adb_reboot &&
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
+ fixup_from_recovery ||
die "reboot after override content added failed `usb_status`"
if ${overlayfs_needed}; then
@@ -985,6 +1224,9 @@
B="`adb_cat /vendor/hello 2>&1`"
check_eq "cat: /vendor/hello: Permission denied" "${B}" vendor after reboot w/o root
echo "${GREEN}[ OK ]${NORMAL} /vendor content correct MAC after reboot" >&2
+ # Feed unprivileged log with selinux denials as a result of overlays
+ wait_for_screen
+ adb_sh find /system /vendor </dev/null >/dev/null 2>/dev/null
fi
B="`adb_cat /system/hello`"
check_eq "${A}" "${B}" /system after reboot
@@ -996,6 +1238,17 @@
check_eq "${A}" "${B}" vendor after reboot
echo "${GREEN}[ OK ]${NORMAL} /vendor content remains after reboot" >&2
+check_eq "${SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/hello </dev/null`" system devt after reboot
+check_eq "${VENDOR_DEVT}" "`adb_sh stat --format=%D /vendor/hello </dev/null`" vendor devt after reboot
+check_eq "${SYSTEM_INO}" "`adb_sh stat --format=%i /system/hello </dev/null`" system inode after reboot
+check_eq "${VENDOR_INO}" "`adb_sh stat --format=%i /vendor/hello </dev/null`" vendor inode after reboot
+check_eq "${BASE_SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/bin/stat </dev/null`" base system devt after reboot
+check_eq "${BASE_VENDOR_DEVT}" "`adb_sh stat --format=%D /vendor/bin/stat </dev/null`" base system devt after reboot
+check_eq "${BASE_SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/xbin/su </dev/null`" devt for su after reboot
+
+# Feed log with selinux denials as a result of overlays
+adb_sh find /system /vendor </dev/null >/dev/null 2>/dev/null
+
# Check if the updated libc.so is persistent after reboot.
adb_root &&
adb pull /system/lib/bootstrap/libc.so ${tempdir}/libc.so.fromdevice >/dev/null ||
@@ -1025,10 +1278,17 @@
echo "${ORANGE}[ WARNING ]${NORMAL} wrong vendor image, skipping"
elif [ -z "${ANDROID_HOST_OUT}" ]; then
echo "${ORANGE}[ WARNING ]${NORMAL} please run lunch, skipping"
+elif ! (
+ adb_cat /vendor/build.prop |
+ cmp -s ${ANDROID_PRODUCT_OUT}/vendor/build.prop
+ ) >/dev/null 2>/dev/null; then
+ echo "${ORANGE}[ WARNING ]${NORMAL} vendor image signature mismatch, skipping"
else
- adb reboot fastboot ||
+ wait_for_screen
+ avc_check
+ adb reboot fastboot </dev/null ||
die "fastbootd not supported (wrong adb in path?)"
- any_wait 2m &&
+ any_wait ${ADB_WAIT} &&
inFastboot ||
die "reboot into fastboot to flash vendor `usb_status` (bad bootloader?)"
fastboot flash vendor ||
@@ -1069,8 +1329,9 @@
fastboot reboot ||
die "can not reboot out of fastboot"
echo "${ORANGE}[ WARNING ]${NORMAL} adb after fastboot"
- adb_wait 2m ||
- die "did not reboot after flash `usb_status`"
+ adb_wait ${ADB_WAIT} ||
+ fixup_from_recovery ||
+ die "did not reboot after formatting ${scratch_cpartition} `usb_status`"
if ${overlayfs_needed}; then
adb_root &&
D=`adb_sh df -k </dev/null` &&
@@ -1101,8 +1362,15 @@
check_eq "cat: /vendor/hello: No such file or directory" "${B}" \
--warning vendor content after flash vendor
fi
+
+ check_eq "${SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/hello </dev/null`" system devt after reboot
+ check_eq "${SYSTEM_INO}" "`adb_sh stat --format=%i /system/hello </dev/null`" system inode after reboot
+ check_eq "${BASE_SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/bin/stat </dev/null`" base system devt after reboot
+ check_eq "${BASE_SYSTEM_DEVT}" "`adb_sh stat --format=%D /system/xbin/su </dev/null`" devt for su after reboot
+
fi
+wait_for_screen
echo "${GREEN}[ RUN ]${NORMAL} remove test content (cleanup)" >&2
T=`adb_date`
@@ -1114,7 +1382,7 @@
echo "${ORANGE}[ WARNING ]${NORMAL} adb remount requires a reboot after partial flash (legacy avb)"
L=`adb_logcat -b all -v nsec -t ${T} 2>&1`
adb_reboot &&
- adb_wait 2m &&
+ adb_wait ${ADB_WAIT} &&
adb_root ||
die "failed to reboot"
T=`adb_date`
@@ -1136,14 +1404,15 @@
echo "${GREEN}[ RUN ]${NORMAL} test fastboot flash to ${scratch_partition} recovery" >&2
- adb reboot fastboot ||
+ avc_check
+ adb reboot fastboot </dev/null ||
die "Reboot into fastbootd"
img=${TMPDIR}/adb-remount-test-${$}.img
cleanup() {
rm ${img}
}
dd if=/dev/zero of=${img} bs=4096 count=16 2>/dev/null &&
- fastboot_wait 2m ||
+ fastboot_wait ${FASTBOOT_WAIT} ||
die "reboot into fastboot `usb_status`"
fastboot flash --force ${scratch_partition} ${img}
err=${?}
@@ -1155,9 +1424,9 @@
die "can not reboot out of fastboot"
[ 0 -eq ${err} ] ||
die "fastboot flash ${scratch_partition}"
- adb_wait 2m &&
+ adb_wait ${ADB_WAIT} &&
adb_root ||
- die "did not reboot after flash"
+ die "did not reboot after flashing empty ${scratch_partition} `usb_status`"
T=`adb_date`
D=`adb disable-verity 2>&1`
err=${?}
@@ -1165,7 +1434,7 @@
then
echo "${ORANGE}[ WARNING ]${NORMAL} adb disable-verity requires a reboot after partial flash"
adb_reboot &&
- adb_wait 2m &&
+ adb_wait ${ADB_WAIT} &&
adb_root ||
die "failed to reboot"
T=`adb_date`
@@ -1191,9 +1460,25 @@
echo "${GREEN}[ RUN ]${NORMAL} test raw remount commands" >&2
+fixup_from_fastboot() {
+ inFastboot || return 1
+ if [ -n "${ACTIVE_SLOT}" ]; then
+ local active_slot=`get_active_slot`
+ if [ X"${ACTIVE_SLOT}" != X"${active_slot}" ]; then
+ echo "${ORANGE}[ ERROR ]${NORMAL} Active slot changed from ${ACTIVE_SLOT} to ${active_slot}"
+ else
+ echo "${ORANGE}[ ERROR ]${NORMAL} Active slot to be set to ${ACTIVE_SLOT}"
+ fi >&2
+ fastboot --set-active=${ACTIVE_SLOT}
+ fi
+ fastboot reboot
+ adb_wait ${ADB_WAIT}
+}
+
# Prerequisite is a prepped device from above.
adb_reboot &&
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
+ fixup_from_fastboot ||
die "lost device after reboot to ro state `usb_status`"
adb_sh grep " /vendor .* rw," /proc/mounts >/dev/null </dev/null &&
die "/vendor is not read-only"
@@ -1205,8 +1490,9 @@
# Prerequisite is a prepped device from above.
adb_reboot &&
- adb_wait 2m ||
- die "lost device after reboot to ro state (USB stack broken?)"
+ adb_wait ${ADB_WAIT} ||
+ fixup_from_fastboot ||
+ die "lost device after reboot to ro state `usb_status`"
adb_sh grep " /vendor .* rw," /proc/mounts >/dev/null </dev/null &&
die "/vendor is not read-only"
adb_su remount vendor </dev/null ||
@@ -1225,26 +1511,35 @@
die "/${d}/overlay wipe"
done
adb_reboot &&
- adb_wait 2m ||
- die "lost device after reboot after wipe (USB stack broken?)"
+ adb_wait ${ADB_WAIT} ||
+ fixup_from_fastboot ||
+ die "lost device after reboot after wipe `usb_status`"
adb_sh grep " /vendor .* rw," /proc/mounts >/dev/null </dev/null &&
die "/vendor is not read-only"
adb_su remount vendor </dev/null ||
die "remount command"
+adb_su df -k </dev/null | skip_unrelated_mounts
adb_sh grep " /vendor .* rw," /proc/mounts >/dev/null </dev/null ||
die "/vendor is not read-write"
-adb_sh grep " /system .* rw," /proc/mounts >/dev/null </dev/null &&
+adb_sh grep " \(/system\|/\) .* rw," /proc/mounts >/dev/null </dev/null &&
die "/system is not read-only"
echo "${GREEN}[ OK ]${NORMAL} remount command works from scratch" >&2
-restore
-err=${?}
+if ! restore; then
+ restore() {
+ true
+ }
+ die "failed to restore verity after remount from scratch test"
+fi
-if [ ${err} = 0 ] && ${overlayfs_supported}; then
+err=0
+
+if ${overlayfs_supported}; then
echo "${GREEN}[ RUN ]${NORMAL} test 'adb remount -R'" >&2
+ avc_check
adb_root &&
adb remount -R &&
- adb_wait 2m ||
+ adb_wait ${ADB_WAIT} ||
die "adb remount -R"
if [ "orange" != "`get_property ro.boot.verifiedbootstate`" -o \
"2" = "`get_property partition.system.verified`" ]; then
@@ -1262,7 +1557,7 @@
}
[ ${err} = 0 ] ||
- die "failed to restore verity" >&2
+ die "failed to restore verity"
echo "${GREEN}[ PASSED ]${NORMAL} adb remount" >&2
diff --git a/init/Android.bp b/init/Android.bp
index 69498ac..eaa7fd7 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -68,6 +68,7 @@
"libpropertyinfoparser",
],
shared_libs: [
+ "libbacktrace",
"libbase",
"libbinder",
"libbootloader_message",
@@ -123,8 +124,10 @@
"reboot.cpp",
"reboot_utils.cpp",
"security.cpp",
+ "selabel.cpp",
"selinux.cpp",
"service.cpp",
+ "service_utils.cpp",
"sigchld_handler.cpp",
"subcontext.cpp",
"subcontext.proto",
@@ -171,7 +174,6 @@
exclude_shared_libs: ["libbinder", "libutils"],
},
},
- ldflags: ["-Wl,--rpath,/system/${LIB}/bootstrap"],
}
// Tests
@@ -258,6 +260,7 @@
"rlimit_parser.cpp",
"tokenizer.cpp",
"service.cpp",
+ "service_utils.cpp",
"subcontext.cpp",
"subcontext.proto",
"util.cpp",
diff --git a/init/Android.mk b/init/Android.mk
index b02c926..0a3e8c7 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -52,6 +52,7 @@
first_stage_mount.cpp \
mount_namespace.cpp \
reboot_utils.cpp \
+ selabel.cpp \
selinux.cpp \
switch_root.cpp \
uevent_listener.cpp \
@@ -105,6 +106,10 @@
libcap \
libgsi \
libcom.android.sysprop.apex \
+ liblzma \
+ libdexfile_support \
+ libunwindstack \
+ libbacktrace \
LOCAL_SANITIZE := signed-integer-overflow
# First stage init is weird: it may start without stdout/stderr, and no /proc.
diff --git a/init/README.md b/init/README.md
index c4505fe..6868378 100644
--- a/init/README.md
+++ b/init/README.md
@@ -35,24 +35,14 @@
at the beginning of its execution. It is responsible for the initial
set up of the system.
-Devices that mount /system, /vendor through the first stage mount mechanism
-load all of the files contained within the
+Init loads all of the files contained within the
/{system,vendor,odm}/etc/init/ directories immediately after loading
the primary /init.rc. This is explained in more details in the
Imports section of this file.
-Legacy devices without the first stage mount mechanism do the following:
-1. /init.rc imports /init.${ro.hardware}.rc which is the primary
- vendor supplied .rc file.
-2. During the mount\_all command, the init executable loads all of the
- files contained within the /{system,vendor,odm}/etc/init/ directories.
- These directories are intended for all Actions and Services used after
- file system mounting.
-
-One may specify paths in the mount\_all command line to have it import
-.rc files at the specified paths instead of the default ones listed above.
-This is primarily for supporting factory mode and other non-standard boot
-modes. The three default paths should be used for the normal boot process.
+Legacy devices without the first stage mount mechanism previously were
+able to import init scripts during mount_all, however that is deprecated
+and not allowed for devices launching after Q.
The intention of these directories is:
@@ -88,14 +78,6 @@
conflict resolution when multiple services are added to the system, as
each one will go into a separate file.
-There are two options "early" and "late" in mount\_all command
-which can be set after optional paths. With "--early" set, the
-init executable will skip mounting entries with "latemount" flag
-and triggering fs encryption state event. With "--late" set,
-init executable will only mount entries with "latemount" flag but skip
-importing rc files. By default, no option is set, and mount\_all will
-process all entries in the given fstab.
-
Actions
-------
Actions are named sequences of commands. Actions have a trigger which
@@ -414,7 +396,8 @@
`class_start_post_data <serviceclass>`
> Like `class_start`, but only considers services that were started
- after /data was mounted. Only used for FDE devices.
+ after /data was mounted, and that were running at the time
+ `class_reset_post_data` was called. Only used for FDE devices.
`class_stop <serviceclass>`
> Stop and disable all services of the specified class if they are
@@ -513,10 +496,12 @@
will be updated if the directory exists already.
`mount_all <fstab> [ <path> ]\* [--<option>]`
-> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab and imports .rc files
- at the specified paths (e.g., on the partitions just mounted) with optional
+> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab with optional
options "early" and "late".
- Refer to the section of "Init .rc Files" for detail.
+ With "--early" set, the init executable will skip mounting entries with
+ "latemount" flag and triggering fs encryption state event. With "--late" set,
+ init executable will only mount entries with "latemount" flag. By default,
+ no option is set, and mount\_all will process all entries in the given fstab.
`mount <type> <device> <dir> [ <flag>\* ] [<options>]`
> Attempt to mount the named device at the directory _dir_
@@ -637,8 +622,9 @@
`ro.boot.init_rc` during initial boot.
2. When it imports /{system,vendor,odm}/etc/init/ for first stage mount
devices immediately after importing /init.rc.
- 3. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
- paths during mount_all.
+ 3. (Deprecated) When it imports /{system,vendor,odm}/etc/init/ or .rc files
+ at specified paths during mount_all, not allowed for devices launching
+ after Q.
The order that files are imported is a bit complex for legacy reasons
and to keep backwards compatibility. It is not strictly guaranteed.
diff --git a/init/action.cpp b/init/action.cpp
index 94ccef2..a4f6936 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_errno() == ENOENT) {
+ result.error().as_errno == 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_string());
+ << (result ? "succeeded" : "failed: " + result.error().as_string);
}
}
diff --git a/init/builtins.cpp b/init/builtins.cpp
index ba1c94d..e9d58c6 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -16,6 +16,7 @@
#include "builtins.h"
+#include <android/api-level.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
@@ -62,12 +63,14 @@
#include "action_manager.h"
#include "bootchart.h"
+#include "host_init_stubs.h"
#include "init.h"
#include "mount_namespace.h"
#include "parser.h"
#include "property_service.h"
#include "reboot.h"
#include "rlimit_parser.h"
+#include "selabel.h"
#include "selinux.h"
#include "service.h"
#include "subcontext.h"
@@ -104,35 +107,36 @@
}
}
-static Result<Success> class_start(const std::string& class_name, bool post_data_only) {
+static Result<Success> do_class_start(const BuiltinArguments& args) {
// Do not start a class if it has a property persist.dont_start_class.CLASS set to 1.
- if (android::base::GetBoolProperty("persist.init.dont_start_class." + class_name, false))
+ if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
return Success();
// Starting a class does not start services which are explicitly disabled.
// They must be started individually.
for (const auto& service : ServiceList::GetInstance()) {
- if (service->classnames().count(class_name)) {
- if (post_data_only && !service->is_post_data()) {
- continue;
- }
+ if (service->classnames().count(args[1])) {
if (auto result = service->StartIfNotDisabled(); !result) {
LOG(ERROR) << "Could not start service '" << service->name()
- << "' as part of class '" << class_name << "': " << result.error();
+ << "' as part of class '" << args[1] << "': " << result.error();
}
}
}
return Success();
}
-static Result<Success> do_class_start(const BuiltinArguments& args) {
- return class_start(args[1], false /* post_data_only */);
-}
-
static Result<Success> do_class_start_post_data(const BuiltinArguments& args) {
if (args.context != kInitContext) {
return Error() << "command 'class_start_post_data' only available in init context";
}
- return class_start(args[1], true /* post_data_only */);
+ for (const auto& service : ServiceList::GetInstance()) {
+ if (service->classnames().count(args[1])) {
+ if (auto result = service->StartIfPostData(); !result) {
+ LOG(ERROR) << "Could not start service '" << service->name()
+ << "' as part of class '" << args[1] << "': " << result.error();
+ }
+ }
+ }
+ return Success();
}
static Result<Success> do_class_stop(const BuiltinArguments& args) {
@@ -587,7 +591,7 @@
auto mount_fstab_return_code = fs_mgr_mount_all(&fstab, mount_mode);
property_set(prop_name, std::to_string(t.duration().count()));
- if (import_rc) {
+ if (import_rc && SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
/* Paths of .rc files are specified at the 2nd argument and beyond */
import_late(args.args, 2, path_arg_end);
}
diff --git a/init/devices.cpp b/init/devices.cpp
index 159c75e..5e760d0 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -36,7 +36,7 @@
#include <selinux/android.h>
#include <selinux/selinux.h>
-#include "selinux.h"
+#include "selabel.h"
#include "util.h"
#ifdef _INIT_INIT_H
diff --git a/init/firmware_handler.cpp b/init/firmware_handler.cpp
index 740e82c..c067f6f 100644
--- a/init/firmware_handler.cpp
+++ b/init/firmware_handler.cpp
@@ -80,15 +80,26 @@
return;
}
+ std::vector<std::string> attempted_paths_and_errors;
+
try_loading_again:
+ attempted_paths_and_errors.clear();
for (const auto& firmware_directory : firmware_directories_) {
std::string file = firmware_directory + uevent.firmware;
unique_fd fw_fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
- struct stat sb;
- if (fw_fd != -1 && fstat(fw_fd, &sb) != -1) {
- LoadFirmware(uevent, root, fw_fd, sb.st_size, loading_fd, data_fd);
- return;
+ if (fw_fd == -1) {
+ attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
+ ", open failed: " + strerror(errno));
+ continue;
}
+ struct stat sb;
+ if (fstat(fw_fd, &sb) == -1) {
+ attempted_paths_and_errors.emplace_back("firmware: attempted " + file +
+ ", fstat failed: " + strerror(errno));
+ continue;
+ }
+ LoadFirmware(uevent, root, fw_fd, sb.st_size, loading_fd, data_fd);
+ return;
}
if (booting) {
@@ -100,6 +111,9 @@
}
LOG(ERROR) << "firmware: could not find firmware for " << uevent.firmware;
+ for (const auto& message : attempted_paths_and_errors) {
+ LOG(ERROR) << message;
+ }
// Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
write(loading_fd, "-1", 2);
diff --git a/init/first_stage_init.cpp b/init/first_stage_init.cpp
index 7dd3ad4..5d64f41 100644
--- a/init/first_stage_init.cpp
+++ b/init/first_stage_init.cpp
@@ -33,7 +33,6 @@
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
-#include <cutils/android_reboot.h>
#include <private/android_filesystem_config.h>
#include "debug_ramdisk.h"
@@ -168,13 +167,10 @@
"mode=0755,uid=0,gid=0"));
#undef CHECKCALL
+ SetStdioToDevNull(argv);
// Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
// talk to the outside world...
- // We need to set up stdin/stdout/stderr for child processes forked from first
- // stage init as part of the mount process. This closes /dev/console if the
- // kernel had previously opened it.
- auto reboot_bootloader = [](const char*) { RebootSystem(ANDROID_RB_RESTART2, "bootloader"); };
- InitKernelLogging(argv, reboot_bootloader);
+ InitKernelLogging(argv);
if (!errors.empty()) {
for (const auto& [error_string, error_errno] : errors) {
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index 85fa874..1a5ed28 100644
--- a/init/first_stage_mount.cpp
+++ b/init/first_stage_mount.cpp
@@ -276,14 +276,12 @@
// required_devices_partition_names_. Found partitions will then be removed from it
// for the subsequent member function to check which devices are NOT created.
bool FirstStageMount::InitRequiredDevices() {
- if (required_devices_partition_names_.empty()) {
- return true;
+ if (!InitDeviceMapper()) {
+ return false;
}
- if (IsDmLinearEnabled() || need_dm_verity_) {
- if (!InitDeviceMapper()) {
- return false;
- }
+ if (required_devices_partition_names_.empty()) {
+ return true;
}
auto uevent_callback = [this](const Uevent& uevent) { return UeventCallback(uevent); };
@@ -604,12 +602,6 @@
return;
}
- // Device-mapper might not be ready if the device doesn't use DAP or verity
- // (for example, hikey).
- if (access("/dev/device-mapper", F_OK) && !InitDeviceMapper()) {
- return;
- }
-
// Find the name of the super partition for the GSI. It will either be
// "userdata", or a block device such as an sdcard. There are no by-name
// partitions other than userdata that we support installing GSIs to.
diff --git a/init/host_init_stubs.h b/init/host_init_stubs.h
index 63ceead..f6e9676 100644
--- a/init/host_init_stubs.h
+++ b/init/host_init_stubs.h
@@ -44,6 +44,12 @@
uint32_t HandlePropertySet(const std::string& name, const std::string& value,
const std::string& source_context, const ucred& cr, std::string* error);
+// reboot_utils.h
+inline void SetFatalRebootTarget() {}
+inline void __attribute__((noreturn)) InitFatalReboot() {
+ abort();
+}
+
// selinux.h
int SelinuxGetVendorAndroidVersion();
void SelabelInitialize();
diff --git a/init/init.cpp b/init/init.cpp
index 1f3c2fc..8ce96f6 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -39,7 +39,6 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
-#include <cutils/android_reboot.h>
#include <fs_avb/fs_avb.h>
#include <fs_mgr_vendor_overlay.h>
#include <keyutils.h>
@@ -66,6 +65,7 @@
#include "reboot.h"
#include "reboot_utils.h"
#include "security.h"
+#include "selabel.h"
#include "selinux.h"
#include "sigchld_handler.h"
#include "util.h"
@@ -280,13 +280,13 @@
return control_message_functions;
}
-void HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
+bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
const auto& map = get_control_message_map();
const auto it = map.find(msg);
if (it == map.end()) {
LOG(ERROR) << "Unknown control msg '" << msg << "'";
- return;
+ return false;
}
std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid);
@@ -315,17 +315,19 @@
default:
LOG(ERROR) << "Invalid function target from static map key '" << msg << "': "
<< static_cast<std::underlying_type<ControlTarget>::type>(function.target);
- return;
+ return false;
}
if (svc == nullptr) {
LOG(ERROR) << "Could not find '" << name << "' for ctl." << msg;
- return;
+ return false;
}
if (auto result = function.action(svc); !result) {
LOG(ERROR) << "Could not ctl." << msg << " for '" << name << "': " << result.error();
+ return false;
}
+ return true;
}
static Result<Success> wait_for_coldboot_done_action(const BuiltinArguments& args) {
@@ -603,17 +605,6 @@
}
}
-static void InitAborter(const char* abort_message) {
- // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
- // simply abort instead of trying to reboot the system.
- if (getpid() != 1) {
- android::base::DefaultAborter(abort_message);
- return;
- }
-
- RebootSystem(ANDROID_RB_RESTART2, "bootloader");
-}
-
static void GlobalSeccomp() {
import_kernel_cmdline(false, [](const std::string& key, const std::string& value,
bool in_qemu) {
@@ -661,8 +652,8 @@
boot_clock::time_point start_time = boot_clock::now();
- // We need to set up stdin/stdout/stderr again now that we're running in init's context.
- InitKernelLogging(argv, InitAborter);
+ SetStdioToDevNull(argv);
+ InitKernelLogging(argv);
LOG(INFO) << "init second stage started!";
// Set init and its forked children's oom_adj.
diff --git a/init/init.h b/init/init.h
index a76da20..90ead0e 100644
--- a/init/init.h
+++ b/init/init.h
@@ -40,7 +40,7 @@
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list);
Parser CreateServiceOnlyParser(ServiceList& service_list);
-void HandleControlMessage(const std::string& msg, const std::string& arg, pid_t pid);
+bool HandleControlMessage(const std::string& msg, const std::string& arg, pid_t pid);
void property_changed(const std::string& name, const std::string& value);
diff --git a/init/keychords.cpp b/init/keychords.cpp
index f5ac44f..d0ca3e7 100644
--- a/init/keychords.cpp
+++ b/init/keychords.cpp
@@ -41,7 +41,7 @@
Keychords::~Keychords() noexcept {
if (inotify_fd_ >= 0) {
- epoll_->UnregisterHandler(inotify_fd_).IgnoreError();
+ epoll_->UnregisterHandler(inotify_fd_);
::close(inotify_fd_);
}
while (!registration_.empty()) GeteventCloseDevice(registration_.begin()->first);
@@ -212,7 +212,7 @@
auto it = registration_.find(device);
if (it == registration_.end()) return;
auto fd = (*it).second;
- epoll_->UnregisterHandler(fd).IgnoreError();
+ epoll_->UnregisterHandler(fd);
registration_.erase(it);
::close(fd);
}
diff --git a/init/keychords_test.cpp b/init/keychords_test.cpp
index e5a6fd3..a3baeb1 100644
--- a/init/keychords_test.cpp
+++ b/init/keychords_test.cpp
@@ -213,7 +213,7 @@
}
void TestFrame::RelaxForMs(std::chrono::milliseconds wait) {
- epoll_.Wait(wait).IgnoreError();
+ epoll_.Wait(wait);
}
void TestFrame::SetChord(int key, bool value) {
diff --git a/init/mount_handler.cpp b/init/mount_handler.cpp
index c8f0e76..b0b63c5 100644
--- a/init/mount_handler.cpp
+++ b/init/mount_handler.cpp
@@ -121,7 +121,7 @@
}
MountHandler::~MountHandler() {
- if (fp_) epoll_->UnregisterHandler(fileno(fp_.get())).IgnoreError();
+ if (fp_) epoll_->UnregisterHandler(fileno(fp_.get()));
}
void MountHandler::MountHandlerFunction() {
diff --git a/init/mount_namespace.cpp b/init/mount_namespace.cpp
index 5305dc7..12144c1 100644
--- a/init/mount_namespace.cpp
+++ b/init/mount_namespace.cpp
@@ -79,6 +79,38 @@
return updatable;
}
+static bool ActivateFlattenedApexesIfPossible() {
+ if (IsRecoveryMode() || IsApexUpdatable()) {
+ return true;
+ }
+
+ constexpr const char kSystemApex[] = "/system/apex";
+ constexpr const char kApexTop[] = "/apex";
+ if (mount(kSystemApex, kApexTop, nullptr, MS_BIND, nullptr) != 0) {
+ PLOG(ERROR) << "Could not bind mount " << kSystemApex << " to " << kApexTop;
+ return false;
+ }
+
+ // Special casing for the runtime APEX
+ constexpr const char kRuntimeApexMountPath[] = "/system/apex/com.android.runtime";
+ static const std::vector<std::string> kRuntimeApexDirNames = {"com.android.runtime.release",
+ "com.android.runtime.debug"};
+ bool success = false;
+ for (const auto& name : kRuntimeApexDirNames) {
+ std::string path = std::string(kSystemApex) + "/" + name;
+ if (access(path.c_str(), F_OK) == 0) {
+ if (mount(path.c_str(), kRuntimeApexMountPath, nullptr, MS_BIND, nullptr) == 0) {
+ success = true;
+ break;
+ }
+ }
+ }
+ if (!success) {
+ PLOG(ERROR) << "Failed to bind mount the runtime APEX to " << kRuntimeApexMountPath;
+ }
+ return success;
+}
+
static android::base::unique_fd bootstrap_ns_fd;
static android::base::unique_fd default_ns_fd;
@@ -129,6 +161,8 @@
default_ns_id = GetMountNamespaceId();
}
+ success &= ActivateFlattenedApexesIfPossible();
+
LOG(INFO) << "SetupMountNamespaces done";
return success;
}
diff --git a/init/property_service.cpp b/init/property_service.cpp
index a1e9551..ab5dd61 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -473,8 +473,9 @@
}
if (StartsWith(name, "ctl.")) {
- HandleControlMessage(name.c_str() + 4, value, cr.pid);
- return PROP_SUCCESS;
+ return HandleControlMessage(name.c_str() + 4, value, cr.pid)
+ ? PROP_SUCCESS
+ : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
}
// sys.powerctl is a special property that is used to make the device reboot. We want to log
@@ -885,8 +886,12 @@
load_properties_from_file("/system/build.prop", nullptr, &properties);
load_properties_from_file("/vendor/default.prop", nullptr, &properties);
load_properties_from_file("/vendor/build.prop", nullptr, &properties);
- load_properties_from_file("/odm/default.prop", nullptr, &properties);
- load_properties_from_file("/odm/build.prop", nullptr, &properties);
+ if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {
+ load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);
+ } else {
+ load_properties_from_file("/odm/default.prop", nullptr, &properties);
+ load_properties_from_file("/odm/build.prop", nullptr, &properties);
+ }
load_properties_from_file("/product/build.prop", nullptr, &properties);
load_properties_from_file("/product_services/build.prop", nullptr, &properties);
load_properties_from_file("/factory/factory.prop", "ro.*", &properties);
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 0966b6c..54f68bb 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -527,13 +527,13 @@
// start all animation classes if stopped.
if (do_shutdown_animation) {
- service->Start().IgnoreError();
+ service->Start();
}
service->SetShutdownCritical(); // will not check animation class separately
}
if (do_shutdown_animation) {
- bootAnim->Start().IgnoreError();
+ bootAnim->Start();
surfaceFlinger->SetShutdownCritical();
bootAnim->SetShutdownCritical();
}
diff --git a/init/reboot_utils.cpp b/init/reboot_utils.cpp
index 9610304..d1a712f 100644
--- a/init/reboot_utils.cpp
+++ b/init/reboot_utils.cpp
@@ -19,14 +19,40 @@
#include <sys/syscall.h>
#include <unistd.h>
-#include <android-base/logging.h>
-#include <cutils/android_reboot.h>
+#include <string>
+
+#include "android-base/file.h"
+#include "android-base/logging.h"
+#include "android-base/strings.h"
+#include "backtrace/Backtrace.h"
+#include "cutils/android_reboot.h"
#include "capabilities.h"
namespace android {
namespace init {
+static std::string init_fatal_reboot_target = "bootloader";
+
+void SetFatalRebootTarget() {
+ std::string cmdline;
+ android::base::ReadFileToString("/proc/cmdline", &cmdline);
+ cmdline = android::base::Trim(cmdline);
+
+ const char kRebootTargetString[] = "androidboot.init_fatal_reboot_target=";
+ auto start_pos = cmdline.find(kRebootTargetString);
+ if (start_pos == std::string::npos) {
+ return; // We already default to bootloader if no setting is provided.
+ }
+ start_pos += sizeof(kRebootTargetString) - 1;
+
+ auto end_pos = cmdline.find(' ', start_pos);
+ // if end_pos isn't found, then we've run off the end, but this is okay as this is the last
+ // entry, and -1 is a valid size for string::substr();
+ auto size = end_pos == std::string::npos ? -1 : end_pos - start_pos;
+ init_fatal_reboot_target = cmdline.substr(start_pos, size);
+}
+
bool IsRebootCapable() {
if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
@@ -75,6 +101,32 @@
abort();
}
+void __attribute__((noreturn)) InitFatalReboot() {
+ auto pid = fork();
+
+ if (pid == -1) {
+ // Couldn't fork, don't even try to backtrace, just reboot.
+ RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
+ } else if (pid == 0) {
+ // Fork a child for safety, since we always want to shut down if something goes wrong, but
+ // its worth trying to get the backtrace, even in the signal handler, since typically it
+ // does work despite not being async-signal-safe.
+ sleep(5);
+ RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
+ }
+
+ // In the parent, let's try to get a backtrace then shutdown.
+ std::unique_ptr<Backtrace> backtrace(
+ Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
+ if (!backtrace->Unwind(0)) {
+ LOG(ERROR) << __FUNCTION__ << ": Failed to unwind callstack.";
+ }
+ for (size_t i = 0; i < backtrace->NumFrames(); i++) {
+ LOG(ERROR) << backtrace->FormatFrameData(i);
+ }
+ RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
+}
+
void InstallRebootSignalHandlers() {
// Instead of panic'ing the kernel as is the default behavior when init crashes,
// we prefer to reboot to bootloader on development builds, as this will prevent
@@ -94,7 +146,7 @@
// RebootSystem uses syscall() which isn't actually async-signal-safe, but our only option
// and probably good enough given this is already an error case and only enabled for
// development builds.
- RebootSystem(ANDROID_RB_RESTART2, "bootloader");
+ InitFatalReboot();
};
action.sa_flags = SA_RESTART;
sigaction(SIGABRT, &action, nullptr);
diff --git a/init/reboot_utils.h b/init/reboot_utils.h
index 073a16a..3fd969e 100644
--- a/init/reboot_utils.h
+++ b/init/reboot_utils.h
@@ -21,11 +21,13 @@
namespace android {
namespace init {
+void SetFatalRebootTarget();
// Determines whether the system is capable of rebooting. This is conservative,
// so if any of the attempts to determine this fail, it will still return true.
bool IsRebootCapable();
// This is a wrapper around the actual reboot calls.
void __attribute__((noreturn)) RebootSystem(unsigned int cmd, const std::string& reboot_target);
+void __attribute__((noreturn)) InitFatalReboot();
void InstallRebootSignalHandlers();
} // namespace init
diff --git a/init/result.h b/init/result.h
index 0e3fd3d..baa680d 100644
--- a/init/result.h
+++ b/init/result.h
@@ -68,14 +68,14 @@
// if (!output) return Error() << "CalculateResult failed: " << output.error();
// UseOutput(*output);
-#ifndef _INIT_RESULT_H
-#define _INIT_RESULT_H
+#pragma once
#include <errno.h>
#include <sstream>
#include <string>
-#include <variant>
+
+#include <android-base/expected.h>
namespace android {
namespace init {
@@ -83,19 +83,24 @@
struct ResultError {
template <typename T>
ResultError(T&& error_string, int error_errno)
- : error_string(std::forward<T>(error_string)), error_errno(error_errno) {}
+ : as_string(std::forward<T>(error_string)), as_errno(error_errno) {}
- std::string error_string;
- int 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.error_string;
+ os << t.as_string;
return os;
}
inline std::ostream& operator<<(std::ostream& os, ResultError&& t) {
- os << std::move(t.error_string);
+ os << std::move(t.as_string);
return os;
}
@@ -105,20 +110,25 @@
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.error_string;
- errno_ = result_error.error_errno;
+ ss_ << result_error.as_string;
+ errno_ = result_error.as_errno;
return std::move(*this);
}
Error&& operator<<(ResultError&& result_error) {
- ss_ << std::move(result_error.error_string);
- errno_ = result_error.error_errno;
+ ss_ << std::move(result_error.as_string);
+ errno_ = result_error.as_errno;
return std::move(*this);
}
@@ -151,63 +161,10 @@
}
template <typename T>
-class [[nodiscard]] Result {
- public:
- Result() {}
-
- template <typename U, typename... V,
- typename = std::enable_if_t<!(std::is_same_v<std::decay_t<U>, Result<T>> &&
- sizeof...(V) == 0)>>
- Result(U&& result, V&&... results)
- : contents_(std::in_place_index_t<0>(), std::forward<U>(result),
- std::forward<V>(results)...) {}
-
- Result(Error&& error) : contents_(std::in_place_index_t<1>(), error.str(), error.get_errno()) {}
- Result(const ResultError& result_error)
- : contents_(std::in_place_index_t<1>(), result_error.error_string,
- result_error.error_errno) {}
- Result(ResultError&& result_error)
- : contents_(std::in_place_index_t<1>(), std::move(result_error.error_string),
- result_error.error_errno) {}
-
- void IgnoreError() const {}
-
- bool has_value() const { return contents_.index() == 0; }
-
- T& value() & { return std::get<0>(contents_); }
- const T& value() const & { return std::get<0>(contents_); }
- T&& value() && { return std::get<0>(std::move(contents_)); }
- const T&& value() const && { return std::get<0>(std::move(contents_)); }
-
- const ResultError& error() const & { return std::get<1>(contents_); }
- ResultError&& error() && { return std::get<1>(std::move(contents_)); }
- const ResultError&& error() const && { return std::get<1>(std::move(contents_)); }
-
- const std::string& error_string() const & { return std::get<1>(contents_).error_string; }
- std::string&& error_string() && { return std::get<1>(std::move(contents_)).error_string; }
- const std::string&& error_string() const && {
- return std::get<1>(std::move(contents_)).error_string;
- }
-
- int error_errno() const { return std::get<1>(contents_).error_errno; }
-
- explicit operator bool() const { return has_value(); }
-
- T& operator*() & { return value(); }
- const T& operator*() const & { return value(); }
- T&& operator*() && { return std::move(value()); }
- const T&& operator*() const && { return std::move(value()); }
-
- T* operator->() { return &value(); }
- const T* operator->() const { return &value(); }
-
- private:
- std::variant<T, ResultError> contents_;
-};
+using Result = android::base::expected<T, ResultError>;
using Success = std::monostate;
} // namespace init
} // namespace android
-#endif
diff --git a/init/result_test.cpp b/init/result_test.cpp
index 327b444..d3d04a0 100644
--- a/init/result_test.cpp
+++ b/init/result_test.cpp
@@ -74,8 +74,8 @@
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
- EXPECT_EQ(0, result.error_errno());
- EXPECT_EQ("failure1", result.error_string());
+ EXPECT_EQ(0, result.error().as_errno);
+ EXPECT_EQ("failure1", result.error().as_string);
}
TEST(result, result_error_empty) {
@@ -83,8 +83,8 @@
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
- EXPECT_EQ(0, result.error_errno());
- EXPECT_EQ("", result.error_string());
+ EXPECT_EQ(0, result.error().as_errno);
+ EXPECT_EQ("", result.error().as_string);
}
TEST(result, result_error_rvalue) {
@@ -98,8 +98,8 @@
ASSERT_FALSE(MakeRvalueErrorResult());
ASSERT_FALSE(MakeRvalueErrorResult().has_value());
- EXPECT_EQ(0, MakeRvalueErrorResult().error_errno());
- EXPECT_EQ("failure1", MakeRvalueErrorResult().error_string());
+ EXPECT_EQ(0, MakeRvalueErrorResult().error().as_errno);
+ EXPECT_EQ("failure1", MakeRvalueErrorResult().error().as_string);
}
TEST(result, result_errno_error) {
@@ -110,8 +110,8 @@
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
- EXPECT_EQ(test_errno, result.error_errno());
- EXPECT_EQ("failure1: "s + strerror(test_errno), result.error_string());
+ 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) {
@@ -122,8 +122,8 @@
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
- EXPECT_EQ(test_errno, result.error_errno());
- EXPECT_EQ(strerror(test_errno), result.error_string());
+ EXPECT_EQ(test_errno, result.error().as_errno);
+ EXPECT_EQ(strerror(test_errno), result.error().as_string);
}
TEST(result, result_error_from_other_result) {
@@ -138,8 +138,8 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(0, result.error_errno());
- EXPECT_EQ(error_text, result.error_string());
+ EXPECT_EQ(0, result.error().as_errno);
+ EXPECT_EQ(error_text, result.error().as_string);
}
TEST(result, result_error_through_ostream) {
@@ -154,8 +154,8 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(0, result.error_errno());
- EXPECT_EQ(error_text, result.error_string());
+ EXPECT_EQ(0, result.error().as_errno);
+ EXPECT_EQ(error_text, result.error().as_string);
}
TEST(result, result_errno_error_through_ostream) {
@@ -174,12 +174,12 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(test_errno, result.error_errno());
- EXPECT_EQ(error_text + ": " + strerror(test_errno), result.error_string());
+ 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>(5, 'a');
+ auto result = Result<std::string>(std::in_place, 5, 'a');
ASSERT_TRUE(result);
ASSERT_TRUE(result.has_value());
@@ -298,8 +298,8 @@
auto result = return_result_result_with_error();
ASSERT_TRUE(result);
ASSERT_FALSE(*result);
- EXPECT_EQ("failure string", result->error_string());
- EXPECT_EQ(6, result->error_errno());
+ 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
@@ -312,7 +312,9 @@
int value_;
};
- auto return_test_struct = []() -> Result<TestStruct> { return {Result<TestStruct>(6), 6}; };
+ 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);
@@ -326,7 +328,7 @@
TEST(result, die_on_get_error_succesful_result) {
Result<std::string> result = "success";
- ASSERT_DEATH(result.error_string(), "");
+ ASSERT_DEATH(result.error(), "");
}
} // namespace init
diff --git a/init/rlimit_parser.cpp b/init/rlimit_parser.cpp
index 1e0754a..476a46a 100644
--- a/init/rlimit_parser.cpp
+++ b/init/rlimit_parser.cpp
@@ -77,7 +77,7 @@
return Error() << "Could not parse hard limit '" << args[3] << "'";
}
- return {resource, limit};
+ return std::pair{resource, limit};
}
} // namespace init
diff --git a/init/rlimit_parser_test.cpp b/init/rlimit_parser_test.cpp
index 659ba8a..e690bf6 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_string());
- EXPECT_EQ(0, result.error_errno());
+ EXPECT_EQ(expected_result, result.error().as_string);
+ EXPECT_EQ(0, result.error().as_errno);
}
TEST(rlimit, RlimitSuccess) {
diff --git a/init/selabel.cpp b/init/selabel.cpp
new file mode 100644
index 0000000..daeb832
--- /dev/null
+++ b/init/selabel.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 "selabel.h"
+
+#include <selinux/android.h>
+
+namespace android {
+namespace init {
+
+namespace {
+
+selabel_handle* sehandle = nullptr;
+}
+
+// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
+// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
+// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
+// one, thus eliminating an extra call to selinux_android_file_context_handle().
+void SelabelInitialize() {
+ sehandle = selinux_android_file_context_handle();
+ selinux_android_set_sehandle(sehandle);
+}
+
+// A C++ wrapper around selabel_lookup() using the cached sehandle.
+// If sehandle is null, this returns success with an empty context.
+bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
+ result->clear();
+
+ if (!sehandle) return true;
+
+ char* context;
+ if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
+ return false;
+ }
+ *result = context;
+ free(context);
+ return true;
+}
+
+// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
+// If sehandle is null, this returns success with an empty context.
+bool SelabelLookupFileContextBestMatch(const std::string& key,
+ const std::vector<std::string>& aliases, int type,
+ std::string* result) {
+ result->clear();
+
+ if (!sehandle) return true;
+
+ std::vector<const char*> c_aliases;
+ for (const auto& alias : aliases) {
+ c_aliases.emplace_back(alias.c_str());
+ }
+ c_aliases.emplace_back(nullptr);
+
+ char* context;
+ if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
+ return false;
+ }
+ *result = context;
+ free(context);
+ return true;
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/selabel.h b/init/selabel.h
new file mode 100644
index 0000000..5d590b2
--- /dev/null
+++ b/init/selabel.h
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+
+namespace android {
+namespace init {
+
+void SelabelInitialize();
+bool SelabelLookupFileContext(const std::string& key, int type, std::string* result);
+bool SelabelLookupFileContextBestMatch(const std::string& key,
+ const std::vector<std::string>& aliases, int type,
+ std::string* result);
+
+} // namespace init
+} // namespace android
diff --git a/init/selinux.cpp b/init/selinux.cpp
index 8a63363..54be086 100644
--- a/init/selinux.cpp
+++ b/init/selinux.cpp
@@ -60,7 +60,6 @@
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/unique_fd.h>
-#include <cutils/android_reboot.h>
#include <fs_avb/fs_avb.h>
#include <selinux/android.h>
@@ -80,8 +79,6 @@
namespace {
-selabel_handle* sehandle = nullptr;
-
enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
EnforcingStatus StatusFromCmdline() {
@@ -522,9 +519,7 @@
// This function initializes SELinux then execs init to run in the init SELinux context.
int SetupSelinux(char** argv) {
- android::base::InitLogging(argv, &android::base::KernelLogger, [](const char*) {
- RebootSystem(ANDROID_RB_RESTART2, "bootloader");
- });
+ InitKernelLogging(argv);
if (REBOOT_BOOTLOADER_ON_PANIC) {
InstallRebootSignalHandlers();
@@ -557,54 +552,5 @@
return 1;
}
-// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache
-// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It
-// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide
-// one, thus eliminating an extra call to selinux_android_file_context_handle().
-void SelabelInitialize() {
- sehandle = selinux_android_file_context_handle();
- selinux_android_set_sehandle(sehandle);
-}
-
-// A C++ wrapper around selabel_lookup() using the cached sehandle.
-// If sehandle is null, this returns success with an empty context.
-bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
- result->clear();
-
- if (!sehandle) return true;
-
- char* context;
- if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) {
- return false;
- }
- *result = context;
- free(context);
- return true;
-}
-
-// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle.
-// If sehandle is null, this returns success with an empty context.
-bool SelabelLookupFileContextBestMatch(const std::string& key,
- const std::vector<std::string>& aliases, int type,
- std::string* result) {
- result->clear();
-
- if (!sehandle) return true;
-
- std::vector<const char*> c_aliases;
- for (const auto& alias : aliases) {
- c_aliases.emplace_back(alias.c_str());
- }
- c_aliases.emplace_back(nullptr);
-
- char* context;
- if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) {
- return false;
- }
- *result = context;
- free(context);
- return true;
-}
-
} // namespace init
} // namespace android
diff --git a/init/selinux.h b/init/selinux.h
index c7d6647..63ad470 100644
--- a/init/selinux.h
+++ b/init/selinux.h
@@ -14,11 +14,7 @@
* limitations under the License.
*/
-#ifndef _INIT_SELINUX_H
-#define _INIT_SELINUX_H
-
-#include <string>
-#include <vector>
+#pragma once
namespace android {
namespace init {
@@ -29,15 +25,7 @@
void SelinuxSetupKernelLogging();
int SelinuxGetVendorAndroidVersion();
-void SelabelInitialize();
-bool SelabelLookupFileContext(const std::string& key, int type, std::string* result);
-bool SelabelLookupFileContextBestMatch(const std::string& key,
- const std::vector<std::string>& aliases, int type,
- std::string* result);
-
static constexpr char kEnvSelinuxStartedAt[] = "SELINUX_STARTED_AT";
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/service.cpp b/init/service.cpp
index 2f96681..8fe5b30 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -21,12 +21,10 @@
#include <linux/input.h>
#include <linux/securebits.h>
#include <sched.h>
-#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
-#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
@@ -36,7 +34,6 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
-#include <android-base/unique_fd.h>
#include <hidl-util/FQName.h>
#include <processgroup/processgroup.h>
#include <selinux/selinux.h>
@@ -46,6 +43,7 @@
#include "util.h"
#if defined(__ANDROID__)
+#include <ApexProperties.sysprop.h>
#include <android/api-level.h>
#include <sys/system_properties.h>
@@ -64,7 +62,6 @@
using android::base::Split;
using android::base::StartsWith;
using android::base::StringPrintf;
-using android::base::unique_fd;
using android::base::WriteStringToFile;
namespace android {
@@ -106,87 +103,6 @@
return computed_context;
}
-Result<Success> Service::SetUpMountNamespace() const {
- constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
-
- // Recursively remount / as slave like zygote does so unmounting and mounting /proc
- // doesn't interfere with the parent namespace's /proc mount. This will also
- // prevent any other mounts/unmounts initiated by the service from interfering
- // with the parent namespace but will still allow mount events from the parent
- // namespace to propagate to the child.
- if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
- return ErrnoError() << "Could not remount(/) recursively as slave";
- }
-
- // umount() then mount() /proc and/or /sys
- // Note that it is not sufficient to mount with MS_REMOUNT.
- if (namespace_flags_ & CLONE_NEWPID) {
- if (umount("/proc") == -1) {
- return ErrnoError() << "Could not umount(/proc)";
- }
- if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
- return ErrnoError() << "Could not mount(/proc)";
- }
- }
- bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(),
- [](const auto& entry) { return entry.first == CLONE_NEWNET; });
- if (remount_sys) {
- if (umount2("/sys", MNT_DETACH) == -1) {
- return ErrnoError() << "Could not umount(/sys)";
- }
- if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
- return ErrnoError() << "Could not mount(/sys)";
- }
- }
- return Success();
-}
-
-Result<Success> Service::SetUpPidNamespace() const {
- if (prctl(PR_SET_NAME, name_.c_str()) == -1) {
- return ErrnoError() << "Could not set name";
- }
-
- pid_t child_pid = fork();
- if (child_pid == -1) {
- return ErrnoError() << "Could not fork init inside the PID namespace";
- }
-
- if (child_pid > 0) {
- // So that we exit with the right status.
- static int init_exitstatus = 0;
- signal(SIGTERM, [](int) { _exit(init_exitstatus); });
-
- pid_t waited_pid;
- int status;
- while ((waited_pid = wait(&status)) > 0) {
- // This loop will end when there are no processes left inside the
- // PID namespace or when the init process inside the PID namespace
- // gets a signal.
- if (waited_pid == child_pid) {
- init_exitstatus = status;
- }
- }
- if (!WIFEXITED(init_exitstatus)) {
- _exit(EXIT_FAILURE);
- }
- _exit(WEXITSTATUS(init_exitstatus));
- }
- return Success();
-}
-
-Result<Success> Service::EnterNamespaces() const {
- for (const auto& [nstype, path] : namespaces_to_enter_) {
- auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
- if (fd == -1) {
- return ErrnoError() << "Could not open namespace at " << path;
- }
- if (setns(fd, nstype) == -1) {
- return ErrnoError() << "Could not setns() namespace at " << path;
- }
- }
- return Success();
-}
-
static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
std::vector<std::string> expanded_args;
std::vector<char*> c_strings;
@@ -229,16 +145,16 @@
flags_(flags),
pid_(0),
crash_count_(0),
- uid_(uid),
- gid_(gid),
- supp_gids_(supp_gids),
- namespace_flags_(namespace_flags),
+ proc_attr_{.ioprio_class = IoSchedClass_NONE,
+ .ioprio_pri = 0,
+ .uid = uid,
+ .gid = gid,
+ .supp_gids = supp_gids,
+ .priority = 0},
+ namespaces_{.flags = namespace_flags},
seclabel_(seclabel),
onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
"onrestart", {}),
- ioprio_class_(IoSchedClass_NONE),
- ioprio_pri_(0),
- priority_(0),
oom_score_adjust_(-1000),
start_order_(0),
args_(args) {}
@@ -271,24 +187,18 @@
<< ") process group...";
int r;
if (signal == SIGTERM) {
- r = killProcessGroupOnce(uid_, pid_, signal);
+ r = killProcessGroupOnce(proc_attr_.uid, pid_, signal);
} else {
- r = killProcessGroup(uid_, pid_, signal);
+ r = killProcessGroup(proc_attr_.uid, pid_, signal);
}
if (r == 0) process_cgroup_empty_ = true;
}
}
-void Service::SetProcessAttributes() {
- for (const auto& rlimit : rlimits_) {
- if (setrlimit(rlimit.first, &rlimit.second) == -1) {
- LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
- rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
- }
- }
+void Service::SetProcessAttributesAndCaps() {
// Keep capabilites on uid change.
- if (capabilities_ && uid_) {
+ if (capabilities_ && proc_attr_.uid) {
// If Android is running in a container, some securebits might already
// be locked, so don't change those.
unsigned long securebits = prctl(PR_GET_SECUREBITS);
@@ -301,37 +211,21 @@
}
}
- // TODO: work out why this fails for `console` then upgrade to FATAL.
- if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
+ if (auto result = SetProcessAttributes(proc_attr_); !result) {
+ LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
+ }
- if (gid_) {
- if (setgid(gid_) != 0) {
- PLOG(FATAL) << "setgid failed for " << name_;
- }
- }
- if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
- PLOG(FATAL) << "setgroups failed for " << name_;
- }
- if (uid_) {
- if (setuid(uid_) != 0) {
- PLOG(FATAL) << "setuid failed for " << name_;
- }
- }
if (!seclabel_.empty()) {
if (setexeccon(seclabel_.c_str()) < 0) {
PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
}
}
- if (priority_ != 0) {
- if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
- PLOG(FATAL) << "setpriority failed for " << name_;
- }
- }
+
if (capabilities_) {
if (!SetCapsForExec(*capabilities_)) {
LOG(FATAL) << "cannot set capabilities for " << name_;
}
- } else if (uid_) {
+ } else if (proc_attr_.uid) {
// Inheritable caps can be non-zero when running in a container.
if (!DropInheritableCaps()) {
LOG(FATAL) << "cannot drop inheritable caps for " << name_;
@@ -372,10 +266,17 @@
return;
}
+#if defined(__ANDROID__)
+ static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
+#else
+ static bool is_apex_updatable = false;
+#endif
+ const bool is_process_updatable = !pre_apexd_ && is_apex_updatable;
+
// If we crash > 4 times in 4 minutes or before boot_completed,
// reboot into bootloader or set crashing property
boot_clock::time_point now = boot_clock::now();
- if (((flags_ & SVC_CRITICAL) || !pre_apexd_) && !(flags_ & SVC_RESTART)) {
+ if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
if (now < time_crashed_ + 4min || !boot_completed) {
if (++crash_count_ > 4) {
@@ -450,7 +351,7 @@
Result<Success> Service::ParseConsole(std::vector<std::string>&& args) {
flags_ |= SVC_CONSOLE;
- console_ = args.size() > 1 ? "/dev/" + args[1] : "";
+ proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
return Success();
}
@@ -469,13 +370,13 @@
if (args[1] != "net") {
return Error() << "Init only supports entering network namespaces";
}
- if (!namespaces_to_enter_.empty()) {
+ if (!namespaces_.namespaces_to_enter.empty()) {
return Error() << "Only one network namespace may be entered";
}
// Network namespaces require that /sys is remounted, otherwise the old adapters will still be
// present. Therefore, they also require mount namespaces.
- namespace_flags_ |= CLONE_NEWNS;
- namespaces_to_enter_.emplace_back(CLONE_NEWNET, std::move(args[2]));
+ namespaces_.flags |= CLONE_NEWNS;
+ namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
return Success();
}
@@ -484,22 +385,22 @@
if (!gid) {
return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
}
- gid_ = *gid;
+ proc_attr_.gid = *gid;
for (std::size_t n = 2; n < args.size(); n++) {
gid = DecodeUid(args[n]);
if (!gid) {
return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
}
- supp_gids_.emplace_back(*gid);
+ proc_attr_.supp_gids.emplace_back(*gid);
}
return Success();
}
Result<Success> Service::ParsePriority(std::vector<std::string>&& args) {
- priority_ = 0;
- if (!ParseInt(args[1], &priority_,
- static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
+ proc_attr_.priority = 0;
+ if (!ParseInt(args[1], &proc_attr_.priority,
+ static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
return Error() << StringPrintf("process priority value must be range %d - %d",
ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
@@ -539,16 +440,16 @@
}
Result<Success> Service::ParseIoprio(std::vector<std::string>&& args) {
- if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
+ if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
return Error() << "priority value must be range 0 - 7";
}
if (args[1] == "rt") {
- ioprio_class_ = IoSchedClass_RT;
+ proc_attr_.ioprio_class = IoSchedClass_RT;
} else if (args[1] == "be") {
- ioprio_class_ = IoSchedClass_BE;
+ proc_attr_.ioprio_class = IoSchedClass_BE;
} else if (args[1] == "idle") {
- ioprio_class_ = IoSchedClass_IDLE;
+ proc_attr_.ioprio_class = IoSchedClass_IDLE;
} else {
return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
}
@@ -605,11 +506,11 @@
Result<Success> Service::ParseNamespace(std::vector<std::string>&& args) {
for (size_t i = 1; i < args.size(); i++) {
if (args[i] == "pid") {
- namespace_flags_ |= CLONE_NEWPID;
+ namespaces_.flags |= CLONE_NEWPID;
// PID namespaces require mount namespaces.
- namespace_flags_ |= CLONE_NEWNS;
+ namespaces_.flags |= CLONE_NEWNS;
} else if (args[i] == "mnt") {
- namespace_flags_ |= CLONE_NEWNS;
+ namespaces_.flags |= CLONE_NEWNS;
} else {
return Error() << "namespace must be 'pid' or 'mnt'";
}
@@ -666,7 +567,7 @@
auto rlimit = ParseRlimit(args);
if (!rlimit) return rlimit.error();
- rlimits_.emplace_back(*rlimit);
+ proc_attr_.rlimits.emplace_back(*rlimit);
return Success();
}
@@ -776,7 +677,7 @@
if (!uid) {
return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
}
- uid_ = *uid;
+ proc_attr_.uid = *uid;
return Success();
}
@@ -877,8 +778,8 @@
flags_ |= SVC_EXEC;
is_exec_service_running_ = true;
- LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid_ << " gid "
- << gid_ << "+" << supp_gids_.size() << " context "
+ LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
+ << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
<< (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
return Success();
@@ -912,16 +813,16 @@
bool needs_console = (flags_ & SVC_CONSOLE);
if (needs_console) {
- if (console_.empty()) {
- console_ = default_console;
+ if (proc_attr_.console.empty()) {
+ proc_attr_.console = default_console;
}
// Make sure that open call succeeds to ensure a console driver is
// properly registered for the device node
- int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
+ int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
if (console_fd < 0) {
flags_ |= SVC_DISABLED;
- return ErrnoError() << "Couldn't open console '" << console_ << "'";
+ return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
}
close(console_fd);
}
@@ -956,8 +857,8 @@
LOG(INFO) << "starting service '" << name_ << "'...";
pid_t pid = -1;
- if (namespace_flags_) {
- pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
+ if (namespaces_.flags) {
+ pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
} else {
pid = fork();
}
@@ -965,33 +866,9 @@
if (pid == 0) {
umask(077);
- if (auto result = EnterNamespaces(); !result) {
- LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error();
- }
-
-#if defined(__ANDROID__)
- if (pre_apexd_) {
- if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
- LOG(FATAL) << "Service '" << name_ << "' could not enter "
- << "into the bootstrap mount namespace";
- }
- }
-#endif
-
- if (namespace_flags_ & CLONE_NEWNS) {
- if (auto result = SetUpMountNamespace(); !result) {
- LOG(FATAL) << "Service '" << name_
- << "' could not set up mount namespace: " << result.error();
- }
- }
-
- if (namespace_flags_ & CLONE_NEWPID) {
- // This will fork again to run an init process inside the PID
- // namespace.
- if (auto result = SetUpPidNamespace(); !result) {
- LOG(FATAL) << "Service '" << name_
- << "' could not set up PID namespace: " << result.error();
- }
+ if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result) {
+ LOG(FATAL) << "Service '" << name_
+ << "' failed to set up namespaces: " << result.error();
}
for (const auto& [key, value] : environment_vars_) {
@@ -1001,58 +878,13 @@
std::for_each(descriptors_.begin(), descriptors_.end(),
std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
- // See if there were "writepid" instructions to write to files under cpuset path.
- std::string cpuset_path;
- if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
- auto cpuset_predicate = [&cpuset_path](const std::string& path) {
- return StartsWith(path, cpuset_path + "/");
- };
- auto iter =
- std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
- if (iter == writepid_files_.end()) {
- // There were no "writepid" instructions for cpusets, check if the system default
- // cpuset is specified to be used for the process.
- std::string default_cpuset = GetProperty("ro.cpuset.default", "");
- if (!default_cpuset.empty()) {
- // Make sure the cpuset name starts and ends with '/'.
- // A single '/' means the 'root' cpuset.
- if (default_cpuset.front() != '/') {
- default_cpuset.insert(0, 1, '/');
- }
- if (default_cpuset.back() != '/') {
- default_cpuset.push_back('/');
- }
- writepid_files_.push_back(
- StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
- }
- }
- } else {
- LOG(ERROR) << "cpuset cgroup controller is not mounted!";
- }
- std::string pid_str = std::to_string(getpid());
- for (const auto& file : writepid_files_) {
- if (!WriteStringToFile(pid_str, file)) {
- PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
- }
- }
-
- if (ioprio_class_ != IoSchedClass_NONE) {
- if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
- PLOG(ERROR) << "failed to set pid " << getpid()
- << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
- }
- }
-
- if (needs_console) {
- setsid();
- OpenConsole();
- } else {
- ZapStdio();
+ if (auto result = WritePidToFiles(&writepid_files_); !result) {
+ LOG(ERROR) << "failed to write pid to files: " << result.error();
}
// As requested, set our gid, supplemental gids, uid, context, and
// priority. Aborts on failure.
- SetProcessAttributes();
+ SetProcessAttributesAndCaps();
if (!ExpandArgsAndExecv(args_, sigstop_)) {
PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
@@ -1082,19 +914,19 @@
bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
limit_percent_ != -1 || !limit_property_.empty();
- errno = -createProcessGroup(uid_, pid_, use_memcg);
+ errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
if (errno != 0) {
- PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
- << name_ << "'";
+ PLOG(ERROR) << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
+ << ") failed for service '" << name_ << "'";
} else if (use_memcg) {
if (swappiness_ != -1) {
- if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
+ if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
PLOG(ERROR) << "setProcessGroupSwappiness failed";
}
}
if (soft_limit_in_bytes_ != -1) {
- if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
+ if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
PLOG(ERROR) << "setProcessGroupSoftLimit failed";
}
}
@@ -1121,7 +953,7 @@
}
if (computed_limit_in_bytes != size_t(-1)) {
- if (!setProcessGroupLimit(uid_, pid_, computed_limit_in_bytes)) {
+ if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
PLOG(ERROR) << "setProcessGroupLimit failed";
}
}
@@ -1154,10 +986,23 @@
void Service::ResetIfPostData() {
if (post_data_) {
+ if (flags_ & SVC_RUNNING) {
+ running_at_post_data_reset_ = true;
+ }
StopOrReset(SVC_RESET);
}
}
+Result<Success> Service::StartIfPostData() {
+ // Start the service, but only if it was started after /data was mounted,
+ // and it was still running when we reset the post-data services.
+ if (running_at_post_data_reset_) {
+ return Start();
+ }
+
+ return Success();
+}
+
void Service::Stop() {
StopOrReset(SVC_DISABLED);
}
@@ -1228,25 +1073,6 @@
}
}
-void Service::ZapStdio() const {
- int fd;
- fd = open("/dev/null", O_RDWR);
- dup2(fd, 0);
- dup2(fd, 1);
- dup2(fd, 2);
- close(fd);
-}
-
-void Service::OpenConsole() const {
- int fd = open(console_.c_str(), O_RDWR);
- if (fd == -1) fd = open("/dev/null", O_RDWR);
- ioctl(fd, TIOCSCTTY, 0);
- dup2(fd, 0);
- dup2(fd, 1);
- dup2(fd, 2);
- close(fd);
-}
-
ServiceList::ServiceList() {}
ServiceList& ServiceList::GetInstance() {
@@ -1370,7 +1196,7 @@
continue;
}
if (auto result = service->Start(); !result) {
- LOG(ERROR) << result.error_string();
+ LOG(ERROR) << result.error().as_string;
}
}
delayed_service_names_.clear();
diff --git a/init/service.h b/init/service.h
index dc2b128..93b5a5c 100644
--- a/init/service.h
+++ b/init/service.h
@@ -36,6 +36,7 @@
#include "descriptors.h"
#include "keyword_map.h"
#include "parser.h"
+#include "service_utils.h"
#include "subcontext.h"
#define SVC_DISABLED 0x001 // do not autostart with class
@@ -79,6 +80,7 @@
Result<Success> ExecStart();
Result<Success> Start();
Result<Success> StartIfNotDisabled();
+ Result<Success> StartIfPostData();
Result<Success> Enable();
void Reset();
void ResetIfPostData();
@@ -106,16 +108,16 @@
pid_t pid() const { return pid_; }
android::base::boot_clock::time_point time_started() const { return time_started_; }
int crash_count() const { return crash_count_; }
- uid_t uid() const { return uid_; }
- gid_t gid() const { return gid_; }
- unsigned namespace_flags() const { return namespace_flags_; }
- const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
+ uid_t uid() const { return proc_attr_.uid; }
+ gid_t gid() const { return proc_attr_.gid; }
+ unsigned namespace_flags() const { return namespaces_.flags; }
+ const std::vector<gid_t>& supp_gids() const { return proc_attr_.supp_gids; }
const std::string& seclabel() const { return seclabel_; }
const std::vector<int>& keycodes() const { return keycodes_; }
- IoSchedClass ioprio_class() const { return ioprio_class_; }
- int ioprio_pri() const { return ioprio_pri_; }
+ IoSchedClass ioprio_class() const { return proc_attr_.ioprio_class; }
+ int ioprio_pri() const { return proc_attr_.ioprio_pri; }
const std::set<std::string>& interfaces() const { return interfaces_; }
- int priority() const { return priority_; }
+ int priority() const { return proc_attr_.priority; }
int oom_score_adjust() const { return oom_score_adjust_; }
bool is_override() const { return override_; }
bool process_cgroup_empty() const { return process_cgroup_empty_; }
@@ -131,15 +133,10 @@
using OptionParser = Result<Success> (Service::*)(std::vector<std::string>&& args);
class OptionParserMap;
- Result<Success> SetUpMountNamespace() const;
- Result<Success> SetUpPidNamespace() const;
- Result<Success> EnterNamespaces() const;
void NotifyStateChange(const std::string& new_state) const;
void StopOrReset(int how);
- void ZapStdio() const;
- void OpenConsole() const;
void KillProcessGroup(int signal);
- void SetProcessAttributes();
+ void SetProcessAttributesAndCaps();
Result<Success> ParseCapabilities(std::vector<std::string>&& args);
Result<Success> ParseClass(std::vector<std::string>&& args);
@@ -183,7 +180,6 @@
std::string name_;
std::set<std::string> classnames_;
- std::string console_;
unsigned flags_;
pid_t pid_;
@@ -191,13 +187,9 @@
android::base::boot_clock::time_point time_crashed_; // first crash within inspection window
int crash_count_; // number of times crashed within window
- uid_t uid_;
- gid_t gid_;
- std::vector<gid_t> supp_gids_;
std::optional<CapSet> capabilities_;
- unsigned namespace_flags_;
- // Pair of namespace type, path to namespace.
- std::vector<std::pair<int, std::string>> namespaces_to_enter_;
+ ProcessAttributes proc_attr_;
+ NamespaceInfo namespaces_;
std::string seclabel_;
@@ -213,10 +205,6 @@
// keycodes for triggering this service via /dev/input/input*
std::vector<int> keycodes_;
- IoSchedClass ioprio_class_;
- int ioprio_pri_;
- int priority_;
-
int oom_score_adjust_;
int swappiness_ = -1;
@@ -232,8 +220,6 @@
unsigned long start_order_;
- std::vector<std::pair<int, rlimit>> rlimits_;
-
bool sigstop_ = false;
std::chrono::seconds restart_period_ = 5s;
@@ -248,6 +234,8 @@
bool pre_apexd_ = false;
bool post_data_ = false;
+
+ bool running_at_post_data_reset_ = false;
};
class ServiceList {
diff --git a/init/service_utils.cpp b/init/service_utils.cpp
new file mode 100644
index 0000000..17fc9c8
--- /dev/null
+++ b/init/service_utils.cpp
@@ -0,0 +1,265 @@
+/*
+ * 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 "service_utils.h"
+
+#include <grp.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+#include <sys/wait.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <processgroup/processgroup.h>
+
+#include "mount_namespace.h"
+
+using android::base::GetProperty;
+using android::base::StartsWith;
+using android::base::StringPrintf;
+using android::base::unique_fd;
+using android::base::WriteStringToFile;
+
+namespace android {
+namespace init {
+
+namespace {
+
+Result<Success> EnterNamespace(int nstype, const char* path) {
+ auto fd = unique_fd{open(path, O_RDONLY | O_CLOEXEC)};
+ if (fd == -1) {
+ return ErrnoError() << "Could not open namespace at " << path;
+ }
+ if (setns(fd, nstype) == -1) {
+ return ErrnoError() << "Could not setns() namespace at " << path;
+ }
+ return Success();
+}
+
+Result<Success> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
+ constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
+
+ // Recursively remount / as slave like zygote does so unmounting and mounting /proc
+ // doesn't interfere with the parent namespace's /proc mount. This will also
+ // prevent any other mounts/unmounts initiated by the service from interfering
+ // with the parent namespace but will still allow mount events from the parent
+ // namespace to propagate to the child.
+ if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
+ return ErrnoError() << "Could not remount(/) recursively as slave";
+ }
+
+ // umount() then mount() /proc and/or /sys
+ // Note that it is not sufficient to mount with MS_REMOUNT.
+ if (remount_proc) {
+ if (umount("/proc") == -1) {
+ return ErrnoError() << "Could not umount(/proc)";
+ }
+ if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
+ return ErrnoError() << "Could not mount(/proc)";
+ }
+ }
+ if (remount_sys) {
+ if (umount2("/sys", MNT_DETACH) == -1) {
+ return ErrnoError() << "Could not umount(/sys)";
+ }
+ if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
+ return ErrnoError() << "Could not mount(/sys)";
+ }
+ }
+ return Success();
+}
+
+Result<Success> SetUpPidNamespace(const char* name) {
+ if (prctl(PR_SET_NAME, name) == -1) {
+ return ErrnoError() << "Could not set name";
+ }
+
+ pid_t child_pid = fork();
+ if (child_pid == -1) {
+ return ErrnoError() << "Could not fork init inside the PID namespace";
+ }
+
+ if (child_pid > 0) {
+ // So that we exit with the right status.
+ static int init_exitstatus = 0;
+ signal(SIGTERM, [](int) { _exit(init_exitstatus); });
+
+ pid_t waited_pid;
+ int status;
+ while ((waited_pid = wait(&status)) > 0) {
+ // This loop will end when there are no processes left inside the
+ // PID namespace or when the init process inside the PID namespace
+ // gets a signal.
+ if (waited_pid == child_pid) {
+ init_exitstatus = status;
+ }
+ }
+ if (!WIFEXITED(init_exitstatus)) {
+ _exit(EXIT_FAILURE);
+ }
+ _exit(WEXITSTATUS(init_exitstatus));
+ }
+ return Success();
+}
+
+void ZapStdio() {
+ int fd;
+ fd = open("/dev/null", O_RDWR);
+ dup2(fd, 0);
+ dup2(fd, 1);
+ dup2(fd, 2);
+ close(fd);
+}
+
+void OpenConsole(const std::string& console) {
+ int fd = open(console.c_str(), O_RDWR);
+ if (fd == -1) fd = open("/dev/null", O_RDWR);
+ ioctl(fd, TIOCSCTTY, 0);
+ dup2(fd, 0);
+ dup2(fd, 1);
+ dup2(fd, 2);
+ close(fd);
+}
+
+} // namespace
+
+Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name,
+ bool pre_apexd) {
+ for (const auto& [nstype, path] : info.namespaces_to_enter) {
+ if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
+ return result;
+ }
+ }
+
+#if defined(__ANDROID__)
+ if (pre_apexd) {
+ if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
+ return Error() << "could not enter into the bootstrap mount namespace";
+ }
+ }
+#endif
+
+ if (info.flags & CLONE_NEWNS) {
+ bool remount_proc = info.flags & CLONE_NEWPID;
+ bool remount_sys =
+ std::any_of(info.namespaces_to_enter.begin(), info.namespaces_to_enter.end(),
+ [](const auto& entry) { return entry.first == CLONE_NEWNET; });
+ if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result) {
+ return result;
+ }
+ }
+
+ if (info.flags & CLONE_NEWPID) {
+ // This will fork again to run an init process inside the PID namespace.
+ if (auto result = SetUpPidNamespace(name.c_str()); !result) {
+ return result;
+ }
+ }
+
+ return Success();
+}
+
+Result<Success> SetProcessAttributes(const ProcessAttributes& attr) {
+ if (attr.ioprio_class != IoSchedClass_NONE) {
+ if (android_set_ioprio(getpid(), attr.ioprio_class, attr.ioprio_pri)) {
+ PLOG(ERROR) << "failed to set pid " << getpid() << " ioprio=" << attr.ioprio_class
+ << "," << attr.ioprio_pri;
+ }
+ }
+
+ if (!attr.console.empty()) {
+ setsid();
+ OpenConsole(attr.console);
+ } else {
+ if (setpgid(0, getpid()) == -1) {
+ return ErrnoError() << "setpgid failed";
+ }
+ ZapStdio();
+ }
+
+ for (const auto& rlimit : attr.rlimits) {
+ if (setrlimit(rlimit.first, &rlimit.second) == -1) {
+ return ErrnoError() << StringPrintf(
+ "setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed", rlimit.first,
+ rlimit.second.rlim_cur, rlimit.second.rlim_max);
+ }
+ }
+
+ if (attr.gid) {
+ if (setgid(attr.gid) != 0) {
+ return ErrnoError() << "setgid failed";
+ }
+ }
+ if (setgroups(attr.supp_gids.size(), const_cast<gid_t*>(&attr.supp_gids[0])) != 0) {
+ return ErrnoError() << "setgroups failed";
+ }
+ if (attr.uid) {
+ if (setuid(attr.uid) != 0) {
+ return ErrnoError() << "setuid failed";
+ }
+ }
+
+ if (attr.priority != 0) {
+ if (setpriority(PRIO_PROCESS, 0, attr.priority) != 0) {
+ return ErrnoError() << "setpriority failed";
+ }
+ }
+ return Success();
+}
+
+Result<Success> WritePidToFiles(std::vector<std::string>* files) {
+ // See if there were "writepid" instructions to write to files under cpuset path.
+ std::string cpuset_path;
+ if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
+ auto cpuset_predicate = [&cpuset_path](const std::string& path) {
+ return StartsWith(path, cpuset_path + "/");
+ };
+ auto iter = std::find_if(files->begin(), files->end(), cpuset_predicate);
+ if (iter == files->end()) {
+ // There were no "writepid" instructions for cpusets, check if the system default
+ // cpuset is specified to be used for the process.
+ std::string default_cpuset = GetProperty("ro.cpuset.default", "");
+ if (!default_cpuset.empty()) {
+ // Make sure the cpuset name starts and ends with '/'.
+ // A single '/' means the 'root' cpuset.
+ if (default_cpuset.front() != '/') {
+ default_cpuset.insert(0, 1, '/');
+ }
+ if (default_cpuset.back() != '/') {
+ default_cpuset.push_back('/');
+ }
+ files->push_back(
+ StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
+ }
+ }
+ } else {
+ LOG(ERROR) << "cpuset cgroup controller is not mounted!";
+ }
+ std::string pid_str = std::to_string(getpid());
+ for (const auto& file : *files) {
+ if (!WriteStringToFile(pid_str, file)) {
+ return ErrnoError() << "couldn't write " << pid_str << " to " << file;
+ }
+ }
+ return Success();
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/service_utils.h b/init/service_utils.h
new file mode 100644
index 0000000..f7502a9
--- /dev/null
+++ b/init/service_utils.h
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <sys/resource.h>
+#include <sys/types.h>
+
+#include <string>
+#include <vector>
+
+#include <cutils/iosched_policy.h>
+
+#include "result.h"
+
+namespace android {
+namespace init {
+
+struct NamespaceInfo {
+ unsigned flags;
+ // Pair of namespace type, path to name.
+ std::vector<std::pair<int, std::string>> namespaces_to_enter;
+};
+Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd);
+
+struct ProcessAttributes {
+ std::string console;
+ IoSchedClass ioprio_class;
+ int ioprio_pri;
+ std::vector<std::pair<int, rlimit>> rlimits;
+ uid_t uid;
+ gid_t gid;
+ std::vector<gid_t> supp_gids;
+ int priority;
+};
+Result<Success> SetProcessAttributes(const ProcessAttributes& attr);
+
+Result<Success> WritePidToFiles(std::vector<std::string>* files);
+
+} // namespace init
+} // namespace android
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index 092c51c..f9eb83d 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -32,6 +32,7 @@
#if defined(__ANDROID__)
#include <android/api-level.h>
#include "property_service.h"
+#include "selabel.h"
#include "selinux.h"
#else
#include "host_init_stubs.h"
@@ -141,8 +142,8 @@
reply->set_success(true);
} else {
auto* failure = reply->mutable_failure();
- failure->set_error_string(result.error_string());
- failure->set_error_errno(result.error_errno());
+ failure->set_error_string(result.error().as_string);
+ failure->set_error_errno(result.error().as_errno);
}
}
@@ -177,7 +178,7 @@
auto init_message = ReadMessage(init_fd_);
if (!init_message) {
- if (init_message.error_errno() == 0) {
+ if (init_message.error().as_errno == 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_benchmark.cpp b/init/subcontext_benchmark.cpp
index eae03e3..6307993 100644
--- a/init/subcontext_benchmark.cpp
+++ b/init/subcontext_benchmark.cpp
@@ -39,7 +39,7 @@
free(context);
while (state.KeepRunning()) {
- subcontext.Execute(std::vector<std::string>{"return_success"}).IgnoreError();
+ subcontext.Execute(std::vector<std::string>{"return_success"});
}
if (subcontext.pid() > 0) {
diff --git a/init/subcontext_test.cpp b/init/subcontext_test.cpp
index 230203a..c0662a4 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_string(), " ");
+ auto pids = Split(result.error().as_string, " ");
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_string());
+ EXPECT_EQ(Join(expected_words, " "), result.error().as_string);
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_string());
+ EXPECT_EQ("Sane error!", result2.error().as_string);
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_string());
+ ASSERT_EQ(context_string, result.error().as_string);
});
}
@@ -167,7 +167,7 @@
};
auto result = subcontext.ExpandArgs(args);
ASSERT_FALSE(result);
- EXPECT_EQ("Failed to expand '" + args[1] + "'", result.error_string());
+ EXPECT_EQ("Failed to expand '" + args[1] + "'", result.error().as_string);
});
}
diff --git a/init/ueventd.cpp b/init/ueventd.cpp
index 399ea4c..d700c46 100644
--- a/init/ueventd.cpp
+++ b/init/ueventd.cpp
@@ -37,6 +37,7 @@
#include "devices.h"
#include "firmware_handler.h"
#include "modalias_handler.h"
+#include "selabel.h"
#include "selinux.h"
#include "uevent_handler.h"
#include "uevent_listener.h"
diff --git a/init/util.cpp b/init/util.cpp
index 29d7a76..243e5f0 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -40,7 +40,8 @@
#include <selinux/android.h>
#if defined(__ANDROID__)
-#include "selinux.h"
+#include "reboot_utils.h"
+#include "selabel.h"
#else
#include "host_init_stubs.h"
#endif
@@ -425,20 +426,50 @@
return true;
}
-void InitKernelLogging(char** argv, std::function<void(const char*)> abort_function) {
+static void InitAborter(const char* abort_message) {
+ // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
+ // simply abort instead of trying to reboot the system.
+ if (getpid() != 1) {
+ android::base::DefaultAborter(abort_message);
+ return;
+ }
+
+ InitFatalReboot();
+}
+
+// The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
+// console enabled and no initramfs, otherwise it does not provide any fds for stdin/stdout/stderr.
+// SetStdioToDevNull() is used to close these existing fds if they exist and replace them with
+// /dev/null regardless.
+//
+// In the case that these fds are provided by the kernel, the exec of second stage init causes an
+// SELinux denial as it does not have access to /dev/console. In the case that they are not
+// provided, exec of any further process is potentially dangerous as the first fd's opened by that
+// process will take the stdin/stdout/stderr fileno's, which can cause issues if printf(), etc is
+// then used by that process.
+//
+// Lastly, simply calling SetStdioToDevNull() in first stage init is not enough, since first
+// stage init still runs in kernel context, future child processes will not have permissions to
+// access any fds that it opens, including the one opened below for /dev/null. Therefore,
+// SetStdioToDevNull() must be called again in second stage init.
+void SetStdioToDevNull(char** argv) {
// Make stdin/stdout/stderr all point to /dev/null.
int fd = open("/dev/null", O_RDWR);
if (fd == -1) {
int saved_errno = errno;
- android::base::InitLogging(argv, &android::base::KernelLogger, std::move(abort_function));
+ android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
errno = saved_errno;
PLOG(FATAL) << "Couldn't open /dev/null";
}
- dup2(fd, 0);
- dup2(fd, 1);
- dup2(fd, 2);
- if (fd > 2) close(fd);
- android::base::InitLogging(argv, &android::base::KernelLogger, std::move(abort_function));
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+ if (fd > STDERR_FILENO) close(fd);
+}
+
+void InitKernelLogging(char** argv) {
+ SetFatalRebootTarget();
+ android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
}
bool IsRecoveryMode() {
diff --git a/init/util.h b/init/util.h
index 2232a0f..767620b 100644
--- a/init/util.h
+++ b/init/util.h
@@ -63,7 +63,8 @@
bool IsLegalPropertyName(const std::string& name);
-void InitKernelLogging(char** argv, std::function<void(const char*)> abort_function);
+void SetStdioToDevNull(char** argv);
+void InitKernelLogging(char** argv);
bool IsRecoveryMode();
} // namespace init
} // namespace android
diff --git a/init/util_test.cpp b/init/util_test.cpp
index 1b5afba..8bf672c 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_string());
+ EXPECT_EQ("open() failed: No such file or directory", file_contents.error().as_string);
}
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_string());
+ EXPECT_EQ("Skipping insecure file", file_contents.error().as_string);
}
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_string());
+ EXPECT_EQ("Skipping insecure file", file_contents.error().as_string);
}
TEST(util, ReadFileSymbolicLink) {
@@ -65,7 +65,8 @@
auto file_contents = ReadFile("/charger");
EXPECT_EQ(ELOOP, errno);
ASSERT_FALSE(file_contents);
- EXPECT_EQ("open() failed: Too many symbolic links encountered", file_contents.error_string());
+ EXPECT_EQ("open() failed: Too many symbolic links encountered",
+ file_contents.error().as_string);
}
TEST(util, ReadFileSuccess) {
@@ -130,7 +131,7 @@
decoded_uid = DecodeUid("toot");
EXPECT_FALSE(decoded_uid);
- EXPECT_EQ("getpwnam failed: No such file or directory", decoded_uid.error_string());
+ EXPECT_EQ("getpwnam failed: No such file or directory", decoded_uid.error().as_string);
decoded_uid = DecodeUid("123");
EXPECT_TRUE(decoded_uid);
diff --git a/libappfuse/FuseBridgeLoop.cc b/libappfuse/FuseBridgeLoop.cc
index ac94e69..f1ca446 100644
--- a/libappfuse/FuseBridgeLoop.cc
+++ b/libappfuse/FuseBridgeLoop.cc
@@ -353,8 +353,8 @@
}
if (entry->IsClosing()) {
const int mount_id = entry->mount_id();
- callback->OnClosed(mount_id);
bridges_.erase(mount_id);
+ callback->OnClosed(mount_id);
if (bridges_.size() == 0) {
// All bridges are now closed.
return false;
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index 7f9a18a..e171155 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -42,6 +42,7 @@
name: "libbacktrace_headers",
vendor_available: true,
recovery_available: true,
+ native_bridge_supported: true,
export_include_dirs: ["include"],
}
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index 619bc56..319a73a 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -34,6 +34,7 @@
vendor_available: true,
recovery_available: true,
host_supported: true,
+ native_bridge_supported: true,
export_include_dirs: ["include"],
target: {
vendor: {
@@ -57,6 +58,7 @@
},
recovery_available: true,
host_supported: true,
+ native_bridge_supported: true,
srcs: [
"config_utils.cpp",
"canned_fs_config.cpp",
diff --git a/libcutils/fs_config.cpp b/libcutils/fs_config.cpp
index 494a06f..6606030 100644
--- a/libcutils/fs_config.cpp
+++ b/libcutils/fs_config.cpp
@@ -158,8 +158,9 @@
{ 00750, AID_ROOT, AID_SHELL, 0, "data/nativetest64/*" },
{ 00600, AID_ROOT, AID_ROOT, 0, "default.prop" }, // legacy
{ 00600, AID_ROOT, AID_ROOT, 0, "system/etc/prop.default" },
- { 00600, AID_ROOT, AID_ROOT, 0, "odm/build.prop" },
- { 00600, AID_ROOT, AID_ROOT, 0, "odm/default.prop" },
+ { 00600, AID_ROOT, AID_ROOT, 0, "odm/build.prop" }, // legacy; only for P release
+ { 00600, AID_ROOT, AID_ROOT, 0, "odm/default.prop" }, // legacy; only for P release
+ { 00600, AID_ROOT, AID_ROOT, 0, "odm/etc/build.prop" },
{ 00444, AID_ROOT, AID_ROOT, 0, odm_conf_dir + 1 },
{ 00444, AID_ROOT, AID_ROOT, 0, odm_conf_file + 1 },
{ 00444, AID_ROOT, AID_ROOT, 0, oem_conf_dir + 1 },
diff --git a/libmemunreachable/Android.bp b/libmemunreachable/Android.bp
index b78a4c4..62a7266 100644
--- a/libmemunreachable/Android.bp
+++ b/libmemunreachable/Android.bp
@@ -22,6 +22,7 @@
cc_library {
name: "libmemunreachable",
+ vendor_available: true,
defaults: ["libmemunreachable_defaults"],
srcs: [
"Allocator.cpp",
@@ -48,10 +49,23 @@
},
export_include_dirs: ["include"],
local_include_dirs: ["include"],
+ version_script: "libmemunreachable.map",
+}
+
+// Integration test that runs against the public API of libmemunreachable
+cc_test {
+ name: "memunreachable_test",
+ defaults: ["libmemunreachable_defaults"],
+ srcs: [
+ "tests/MemUnreachable_test.cpp",
+ ],
+ shared_libs: ["libmemunreachable"],
+
+ test_suites: ["device-tests"],
}
cc_test {
- name: "memunreachable_test",
+ name: "memunreachable_unit_test",
defaults: ["libmemunreachable_defaults"],
host_supported: true,
srcs: [
@@ -67,8 +81,9 @@
"tests/MemUnreachable_test.cpp",
"tests/ThreadCapture_test.cpp",
],
- shared_libs: [
+ static_libs: [
"libmemunreachable",
+ "libc_malloc_debug_backtrace",
],
},
host: {
diff --git a/libmemunreachable/MemUnreachable.cpp b/libmemunreachable/MemUnreachable.cpp
index 299c320..ce937fd 100644
--- a/libmemunreachable/MemUnreachable.cpp
+++ b/libmemunreachable/MemUnreachable.cpp
@@ -280,6 +280,12 @@
}
bool GetUnreachableMemory(UnreachableMemoryInfo& info, size_t limit) {
+ if (info.version > 0) {
+ MEM_ALOGE("unsupported UnreachableMemoryInfo.version %zu in GetUnreachableMemory",
+ info.version);
+ return false;
+ }
+
int parent_pid = getpid();
int parent_tid = gettid();
diff --git a/libmemunreachable/include/memunreachable/memunreachable.h b/libmemunreachable/include/memunreachable/memunreachable.h
index c028eab..011443f 100644
--- a/libmemunreachable/include/memunreachable/memunreachable.h
+++ b/libmemunreachable/include/memunreachable/memunreachable.h
@@ -28,38 +28,45 @@
namespace android {
struct Leak {
- uintptr_t begin;
- size_t size;
+ uintptr_t begin = 0;
+ size_t size = 0;
- size_t referenced_count;
- size_t referenced_size;
+ size_t referenced_count = 0;
+ size_t referenced_size = 0;
- size_t similar_count;
- size_t similar_size;
- size_t similar_referenced_count;
- size_t similar_referenced_size;
+ size_t similar_count = 0;
+ size_t similar_size = 0;
+ size_t similar_referenced_count = 0;
+ size_t similar_referenced_size = 0;
- size_t total_size;
+ size_t total_size = 0;
static const size_t contents_length = 32;
- char contents[contents_length];
+ char contents[contents_length] = {};
struct Backtrace {
- size_t num_frames;
+ size_t num_frames = 0;
static const size_t max_frames = 16;
- uintptr_t frames[max_frames];
+ uintptr_t frames[max_frames] = {};
+
+ size_t reserved[8] = {};
} backtrace;
+ size_t reserved[8] = {};
+
std::string ToString(bool log_contents) const;
};
struct UnreachableMemoryInfo {
std::vector<Leak> leaks;
- size_t num_leaks;
- size_t leak_bytes;
- size_t num_allocations;
- size_t allocation_bytes;
+ size_t num_leaks = 0;
+ size_t leak_bytes = 0;
+ size_t num_allocations = 0;
+ size_t allocation_bytes = 0;
+
+ size_t version = 0; // Must be 0
+ size_t reserved[8] = {};
UnreachableMemoryInfo() {}
~UnreachableMemoryInfo();
diff --git a/libmemunreachable/libmemunreachable.map b/libmemunreachable/libmemunreachable.map
new file mode 100644
index 0000000..0d0d954
--- /dev/null
+++ b/libmemunreachable/libmemunreachable.map
@@ -0,0 +1,13 @@
+LIBMEMUNREACHABLE {
+ global:
+ LogUnreachableMemory;
+ NoLeaks;
+ extern "C++" {
+ android::GetUnreachableMemory*;
+ android::GetUnreachableMemoryString*;
+ android::Leak::*;
+ android::UnreachableMemoryInfo::*;
+ };
+ local:
+ *;
+};
diff --git a/libmemunreachable/tests/MemUnreachable_test.cpp b/libmemunreachable/tests/MemUnreachable_test.cpp
index bba0c6d..9cb1623 100644
--- a/libmemunreachable/tests/MemUnreachable_test.cpp
+++ b/libmemunreachable/tests/MemUnreachable_test.cpp
@@ -47,7 +47,8 @@
// Trick the compiler into thinking a value on the stack is still referenced.
static void Ref(void** ptr) {
- write(0, ptr, 0);
+ void** volatile storage;
+ storage = ptr;
}
class MemunreachableTest : public ::testing::Test {
@@ -264,4 +265,12 @@
ASSERT_TRUE(LogUnreachableMemory(true, 100));
}
+TEST_F(MemunreachableTest, version) {
+ UnreachableMemoryInfo info;
+ info.version = 1;
+
+ ASSERT_FALSE(GetUnreachableMemory(info));
+ ASSERT_EQ(0U, info.leaks.size());
+}
+
} // namespace android
diff --git a/libnativeloader/Android.bp b/libnativeloader/Android.bp
index 3b77a9e..debc43f 100644
--- a/libnativeloader/Android.bp
+++ b/libnativeloader/Android.bp
@@ -30,6 +30,7 @@
android: {
srcs: [
"library_namespaces.cpp",
+ "native_loader_namespace.cpp",
"public_libraries.cpp",
],
shared_libs: [
diff --git a/libnativeloader/README.md b/libnativeloader/README.md
new file mode 100644
index 0000000..46f6fdd
--- /dev/null
+++ b/libnativeloader/README.md
@@ -0,0 +1,84 @@
+libnativeloader
+===============================================================================
+
+Overview
+-------------------------------------------------------------------------------
+libnativeloader is responsible for loading native shared libraries (`*.so`
+files) inside the Android Runtime (ART). The native shared libraries could be
+app-provided JNI libraries or public native libraries like `libc.so` provided
+by the platform.
+
+The most typical use case of this library is calling `System.loadLibrary(name)`.
+When the method is called, the ART runtime delegates the call to this library
+along with the reference to the classloader where the call was made. Then this
+library finds the linker namespace (named `classloader-namespace`) that is
+associated with the given classloader, and tries to load the requested library
+from the namespace. The actual searching, loading, and linking of the library
+is performed by the dynamic linker.
+
+The linker namespace is created when an APK is loaded into the process, and is
+associated with the classloader that loaded the APK. The linker namespace is
+configured so that only the JNI libraries embedded in the APK is accessible
+from the namespace, thus preventing an APK from loading JNI libraries of other
+APKs.
+
+The linker namespace is also configured differently depending on other
+characteristics of the APK such as whether or not the APK is bundled with the
+platform. In case of the unbundled, i.e., downloaded or updated APK, only the
+public native libraries that is listed in `/system/etc/public.libraries.txt`
+are available from the platform, whereas in case of the bundled, all libraries
+under `/system/lib` are available (i.e. shared). In case when the unbundled
+app is from `/vendor` or `/product` partition, the app is additionally provided
+with the [VNDK-SP](https://source.android.com/devices/architecture/vndk#sp-hal)
+libraries. As the platform is getting modularized with
+[APEX](https://android.googlesource.com/platform/system/apex/+/refs/heads/master/docs/README.md),
+some libraries are no longer provided from platform, but from the APEXes which
+have their own linker namespaces. For example, ICU libraries `libicuuc.so` and
+`libicui18n.so` are from the runtime APEX.
+
+The list of public native libraries is not static. The default set of libraries
+are defined in AOSP, but partners can extend it to include their own libraries.
+Currently, following extensions are available:
+
+- `/vendor/etc/public.libraries.txt`: libraries in `/vendor/lib` that are
+specific to the underlying SoC, e.g. GPU, DSP, etc.
+- `/{system|product}/etc/public.libraries-<companyname>.txt`: libraries in
+`/{system|system}/lib` that a device manufacturer has newly added. The
+libraries should be named as `lib<name>.<companyname>.so` as in
+`libFoo.acme.so`.
+
+Note that, due to the naming constraint requiring `.<companyname>.so` suffix, it
+is prohibited for a device manufacturer to expose an AOSP-defined private
+library, e.g. libgui.so, libart.so, etc., to APKs.
+
+Lastly, libnativeloader is responsible for abstracting the two types of the
+dynamic linker interface: `libdl.so` and `libnativebridge.so`. The former is
+for non-translated, e.g. ARM-on-ARM, libraries, while the latter is for
+loading libraries in a translated environment such as ARM-on-x86.
+
+Implementation
+-------------------------------------------------------------------------------
+Implementation wise, libnativeloader consists of four parts:
+
+- `native_loader.cpp`
+- `library_namespaces.cpp`
+- `native_loader_namespace.cpp`
+- `public_libraries.cpp`
+
+`native_loader.cpp` implements the public interface of this library. It is just
+a thin wrapper around `library_namespaces.cpp` and `native_loader_namespace.cpp`.
+
+`library_namespaces.cpp` implements the singleton class `LibraryNamespaces` which
+is a manager-like entity that is responsible for creating and configuring
+linker namespaces and finding an already created linker namespace for a given
+classloader.
+
+`native_loader_namesapces.cpp` implements the class `NativeLoaderNamespace` that
+models a linker namespace. It's main job is to abstract the two types of the
+dynamic linker interface so that other parts of this library do not have to know
+the differences of the interfaces.
+
+`public_libraries.cpp` is responsible for reading `*.txt` files for the public
+native libraries from the various partitions. It can be considered as a part of
+`LibraryNamespaces` but is separated from it to hide the details of the parsing
+routines.
diff --git a/libnativeloader/library_namespaces.cpp b/libnativeloader/library_namespaces.cpp
index 3839a15..f7f972f 100644
--- a/libnativeloader/library_namespaces.cpp
+++ b/libnativeloader/library_namespaces.cpp
@@ -22,12 +22,13 @@
#include <string>
#include <vector>
-#include "android-base/file.h"
-#include "android-base/logging.h"
-#include "android-base/macros.h"
-#include "android-base/properties.h"
-#include "android-base/strings.h"
-#include "nativehelper/ScopedUtfChars.h"
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <nativehelper/ScopedUtfChars.h>
+
#include "nativeloader/dlext_namespaces.h"
#include "public_libraries.h"
#include "utils.h"
@@ -41,8 +42,6 @@
// vendor and system namespaces.
constexpr const char* kVendorNamespaceName = "sphal";
constexpr const char* kVndkNamespaceName = "vndk";
-constexpr const char* kDefaultNamespaceName = "default";
-constexpr const char* kPlatformNamespaceName = "platform";
constexpr const char* kRuntimeNamespaceName = "runtime";
// classloader-namespace is a linker namespace that is created for the loaded
@@ -167,34 +166,13 @@
LOG_ALWAYS_FATAL_IF(found, "There is already a namespace associated with this classloader");
- uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
- if (is_shared) {
- namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
- }
-
- if (target_sdk_version < 24) {
- namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
- }
-
- NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
-
- bool is_native_bridge = false;
-
- if (parent_ns != nullptr) {
- is_native_bridge = !parent_ns->is_android_namespace();
- } else if (!library_path.empty()) {
- is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
- }
-
std::string system_exposed_libraries = default_public_libraries();
const char* namespace_name = kClassloaderNamespaceName;
- android_namespace_t* vndk_ns = nullptr;
+ bool unbundled_vendor_or_product_app = false;
if ((apk_origin == APK_ORIGIN_VENDOR ||
(apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
!is_shared) {
- LOG_FATAL_IF(is_native_bridge,
- "Unbundled vendor / product apk must not use translated architecture");
-
+ unbundled_vendor_or_product_app = true;
// For vendor / product apks, give access to the vendor / product lib even though
// they are treated as unbundled; the libs and apks are still bundled
// together in the vendor / product partition.
@@ -214,22 +192,12 @@
origin_partition = "unknown";
origin_lib_path = "";
}
-
- LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
- origin_partition);
-
library_path = library_path + ":" + origin_lib_path;
permitted_path = permitted_path + ":" + origin_lib_path;
// Also give access to LLNDK libraries since they are available to vendors
system_exposed_libraries = system_exposed_libraries + ":" + llndk_libraries().c_str();
- // Give access to VNDK-SP libraries from the 'vndk' namespace.
- vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
- if (vndk_ns == nullptr) {
- ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
- }
-
// Different name is useful for debugging
namespace_name = kVendorClassloaderNamespaceName;
ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
@@ -241,120 +209,56 @@
system_exposed_libraries = system_exposed_libraries + ':' + extended_public_libraries();
}
}
- std::string runtime_exposed_libraries = runtime_public_libraries();
- NativeLoaderNamespace native_loader_ns;
- if (!is_native_bridge) {
- // The platform namespace is called "default" for binaries in /system and
- // "platform" for those in the Runtime APEX. Try "platform" first since
- // "default" always exists.
- android_namespace_t* platform_ns = android_get_exported_namespace(kPlatformNamespaceName);
- if (platform_ns == nullptr) {
- platform_ns = android_get_exported_namespace(kDefaultNamespaceName);
- }
-
- android_namespace_t* android_parent_ns;
- if (parent_ns != nullptr) {
- android_parent_ns = parent_ns->get_android_ns();
- } else {
- // Fall back to the platform namespace if no parent is found.
- android_parent_ns = platform_ns;
- }
-
- android_namespace_t* ns =
- android_create_namespace(namespace_name, nullptr, library_path.c_str(), namespace_type,
- permitted_path.c_str(), android_parent_ns);
- if (ns == nullptr) {
- *error_msg = dlerror();
- return nullptr;
- }
-
- // Note that when vendor_ns is not configured this function will return nullptr
- // and it will result in linking vendor_public_libraries_ to the default namespace
- // which is expected behavior in this case.
- android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
-
- android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
-
- if (!android_link_namespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
- *error_msg = dlerror();
- return nullptr;
- }
-
- // Runtime apex does not exist in host, and under certain build conditions.
- if (runtime_ns != nullptr) {
- if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
- *error_msg = dlerror();
- return nullptr;
- }
- }
-
- if (vndk_ns != nullptr && !vndksp_libraries().empty()) {
- // vendor apks are allowed to use VNDK-SP libraries.
- if (!android_link_namespaces(ns, vndk_ns, vndksp_libraries().c_str())) {
- *error_msg = dlerror();
- return nullptr;
- }
- }
-
- if (!vendor_public_libraries().empty()) {
- if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries().c_str())) {
- *error_msg = dlerror();
- return nullptr;
- }
- }
-
- native_loader_ns = NativeLoaderNamespace(ns);
- } else {
- // Same functionality as in the branch above, but calling through native bridge.
-
- native_bridge_namespace_t* platform_ns =
- NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
- if (platform_ns == nullptr) {
- platform_ns = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
- }
-
- native_bridge_namespace_t* native_bridge_parent_namespace;
- if (parent_ns != nullptr) {
- native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
- } else {
- native_bridge_parent_namespace = platform_ns;
- }
-
- native_bridge_namespace_t* ns =
- NativeBridgeCreateNamespace(namespace_name, nullptr, library_path.c_str(), namespace_type,
- permitted_path.c_str(), native_bridge_parent_namespace);
- if (ns == nullptr) {
- *error_msg = NativeBridgeGetError();
- return nullptr;
- }
-
- native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
- native_bridge_namespace_t* runtime_ns = NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
-
- if (!NativeBridgeLinkNamespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
- *error_msg = NativeBridgeGetError();
- return nullptr;
- }
-
- // Runtime apex does not exist in host, and under certain build conditions.
- if (runtime_ns != nullptr) {
- if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
- *error_msg = NativeBridgeGetError();
- return nullptr;
- }
- }
- if (!vendor_public_libraries().empty()) {
- if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries().c_str())) {
- *error_msg = NativeBridgeGetError();
- return nullptr;
- }
- }
-
- native_loader_ns = NativeLoaderNamespace(ns);
+ // Create the app namespace
+ NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
+ auto app_ns =
+ NativeLoaderNamespace::Create(namespace_name, library_path, permitted_path, parent_ns,
+ is_shared, target_sdk_version < 24 /* is_greylist_enabled */);
+ if (app_ns.IsNil()) {
+ *error_msg = app_ns.GetError();
+ return nullptr;
}
- namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
+ // ... and link to other namespaces to allow access to some public libraries
+ bool is_bridged = app_ns.IsBridged();
+
+ auto platform_ns = NativeLoaderNamespace::GetPlatformNamespace(is_bridged);
+ if (!app_ns.Link(platform_ns, system_exposed_libraries)) {
+ *error_msg = app_ns.GetError();
+ return nullptr;
+ }
+
+ auto runtime_ns = NativeLoaderNamespace::GetExportedNamespace(kRuntimeNamespaceName, is_bridged);
+ // Runtime apex does not exist in host, and under certain build conditions.
+ if (!runtime_ns.IsNil()) {
+ if (!app_ns.Link(runtime_ns, runtime_public_libraries())) {
+ *error_msg = app_ns.GetError();
+ return nullptr;
+ }
+ }
+
+ // Give access to VNDK-SP libraries from the 'vndk' namespace.
+ if (unbundled_vendor_or_product_app && !vndksp_libraries().empty()) {
+ auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
+ if (!vndk_ns.IsNil() && !app_ns.Link(vndk_ns, vndksp_libraries())) {
+ *error_msg = app_ns.GetError();
+ return nullptr;
+ }
+ }
+
+ // Note that when vendor_ns is not configured, vendor_ns.IsNil() will be true
+ // and it will result in linking to the default namespace which is expected
+ // behavior in this case.
+ if (!vendor_public_libraries().empty()) {
+ auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
+ if (!app_ns.Link(vendor_ns, vendor_public_libraries())) {
+ *error_msg = dlerror();
+ return nullptr;
+ }
+ }
+
+ namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), app_ns));
return &(namespaces_.back().second);
}
diff --git a/libnativeloader/library_namespaces.h b/libnativeloader/library_namespaces.h
index 103cfac..fd46cdc 100644
--- a/libnativeloader/library_namespaces.h
+++ b/libnativeloader/library_namespaces.h
@@ -25,8 +25,7 @@
#include <list>
#include <string>
-#include "jni.h"
-#include "utils.h"
+#include <jni.h>
namespace android::nativeloader {
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index eeee077..0c29324 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-#include "nativeloader/native_loader.h"
#define LOG_TAG "nativeloader"
+#include "nativeloader/native_loader.h"
+
#include <dlfcn.h>
#include <sys/types.h>
@@ -25,16 +26,17 @@
#include <string>
#include <vector>
-#include "android-base/file.h"
-#include "android-base/macros.h"
-#include "android-base/strings.h"
+#include <android-base/file.h>
+#include <android-base/macros.h>
+#include <android-base/strings.h>
+#include <nativebridge/native_bridge.h>
+#include <nativehelper/ScopedUtfChars.h>
+
#ifdef __ANDROID__
+#include <log/log.h>
#include "library_namespaces.h"
-#include "log/log.h"
#include "nativeloader/dlext_namespaces.h"
#endif
-#include "nativebridge/native_bridge.h"
-#include "nativehelper/ScopedUtfChars.h"
namespace android {
@@ -220,25 +222,12 @@
#if defined(__ANDROID__)
void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
bool* needs_native_bridge, char** error_msg) {
- if (ns->is_android_namespace()) {
- android_dlextinfo extinfo;
- extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
- extinfo.library_namespace = ns->get_android_ns();
-
- void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
- if (handle == nullptr) {
- *error_msg = strdup(dlerror());
- }
- *needs_native_bridge = false;
- return handle;
- } else {
- void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
- if (handle == nullptr) {
- *error_msg = strdup(NativeBridgeGetError());
- }
- *needs_native_bridge = true;
- return handle;
+ void* handle = ns->Load(path);
+ if (handle == nullptr) {
+ *error_msg = ns->GetError();
}
+ *needs_native_bridge = ns->IsBridged();
+ return handle;
}
// native_bridge_namespaces are not supported for callers of this function.
@@ -247,10 +236,9 @@
android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
std::lock_guard<std::mutex> guard(g_namespaces_mutex);
NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
- if (ns != nullptr) {
- return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
+ if (ns != nullptr && !ns->IsBridged()) {
+ return ns->ToRawAndroidNamespace();
}
-
return nullptr;
}
diff --git a/libnativeloader/native_loader_namespace.cpp b/libnativeloader/native_loader_namespace.cpp
new file mode 100644
index 0000000..58ac686
--- /dev/null
+++ b/libnativeloader/native_loader_namespace.cpp
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "nativeloader"
+
+#include "native_loader_namespace.h"
+
+#include <dlfcn.h>
+
+#include <functional>
+
+#include <android-base/strings.h>
+#include <log/log.h>
+#include <nativebridge/native_bridge.h>
+
+#include "nativeloader/dlext_namespaces.h"
+
+namespace android {
+
+namespace {
+
+constexpr const char* kDefaultNamespaceName = "default";
+constexpr const char* kPlatformNamespaceName = "platform";
+
+} // namespace
+
+NativeLoaderNamespace NativeLoaderNamespace::GetExportedNamespace(const std::string& name,
+ bool is_bridged) {
+ if (!is_bridged) {
+ return NativeLoaderNamespace(name, android_get_exported_namespace(name.c_str()));
+ } else {
+ return NativeLoaderNamespace(name, NativeBridgeGetExportedNamespace(name.c_str()));
+ }
+}
+
+char* NativeLoaderNamespace::GetError() const {
+ if (!IsBridged()) {
+ return strdup(dlerror());
+ } else {
+ return strdup(NativeBridgeGetError());
+ }
+}
+
+// The platform namespace is called "default" for binaries in /system and
+// "platform" for those in the Runtime APEX. Try "platform" first since
+// "default" always exists.
+NativeLoaderNamespace NativeLoaderNamespace::GetPlatformNamespace(bool is_bridged) {
+ NativeLoaderNamespace ns = GetExportedNamespace(kPlatformNamespaceName, is_bridged);
+ if (ns.IsNil()) {
+ ns = GetExportedNamespace(kDefaultNamespaceName, is_bridged);
+ }
+ return ns;
+}
+
+NativeLoaderNamespace NativeLoaderNamespace::Create(const std::string& name,
+ const std::string& search_paths,
+ const std::string& permitted_paths,
+ const NativeLoaderNamespace* parent,
+ bool is_shared, bool is_greylist_enabled) {
+ bool is_bridged = false;
+ if (parent != nullptr) {
+ is_bridged = parent->IsBridged();
+ } else if (!search_paths.empty()) {
+ is_bridged = NativeBridgeIsPathSupported(search_paths.c_str());
+ }
+
+ // Fall back to the platform namespace if no parent is set.
+ const NativeLoaderNamespace& effective_parent =
+ parent != nullptr ? *parent : GetPlatformNamespace(is_bridged);
+
+ uint64_t type = ANDROID_NAMESPACE_TYPE_ISOLATED;
+ if (is_shared) {
+ type |= ANDROID_NAMESPACE_TYPE_SHARED;
+ }
+ if (is_greylist_enabled) {
+ type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
+ }
+
+ if (!is_bridged) {
+ android_namespace_t* raw =
+ android_create_namespace(name.c_str(), nullptr, search_paths.c_str(), type,
+ permitted_paths.c_str(), effective_parent.ToRawAndroidNamespace());
+ return NativeLoaderNamespace(name, raw);
+ } else {
+ native_bridge_namespace_t* raw = NativeBridgeCreateNamespace(
+ name.c_str(), nullptr, search_paths.c_str(), type, permitted_paths.c_str(),
+ effective_parent.ToRawNativeBridgeNamespace());
+ return NativeLoaderNamespace(name, raw);
+ }
+}
+
+bool NativeLoaderNamespace::Link(const NativeLoaderNamespace& target,
+ const std::string& shared_libs) const {
+ LOG_ALWAYS_FATAL_IF(shared_libs.empty(), "empty share lib when linking %s to %s",
+ this->name().c_str(), target.name().c_str());
+ if (!IsBridged()) {
+ return android_link_namespaces(this->ToRawAndroidNamespace(), target.ToRawAndroidNamespace(),
+ shared_libs.c_str());
+ } else {
+ return NativeBridgeLinkNamespaces(this->ToRawNativeBridgeNamespace(),
+ target.ToRawNativeBridgeNamespace(), shared_libs.c_str());
+ }
+}
+
+void* NativeLoaderNamespace::Load(const char* lib_name) const {
+ if (!IsBridged()) {
+ android_dlextinfo extinfo;
+ extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
+ extinfo.library_namespace = this->ToRawAndroidNamespace();
+ return android_dlopen_ext(lib_name, RTLD_NOW, &extinfo);
+ } else {
+ return NativeBridgeLoadLibraryExt(lib_name, RTLD_NOW, this->ToRawNativeBridgeNamespace());
+ }
+}
+
+} // namespace android
diff --git a/libnativeloader/native_loader_namespace.h b/libnativeloader/native_loader_namespace.h
index b983a2d..71e4247 100644
--- a/libnativeloader/native_loader_namespace.h
+++ b/libnativeloader/native_loader_namespace.h
@@ -16,13 +16,14 @@
#pragma once
#if defined(__ANDROID__)
-#include <dlfcn.h>
+#include <string>
+#include <variant>
+#include <vector>
-#include "android-base/logging.h"
-#include "android/dlext.h"
-#include "log/log.h"
-#include "nativebridge/native_bridge.h"
-#include "utils.h"
+#include <android-base/logging.h>
+#include <android/dlext.h>
+#include <log/log.h>
+#include <nativebridge/native_bridge.h>
namespace android {
@@ -31,34 +32,40 @@
// x86). Instances of this class are managed by LibraryNamespaces object.
struct NativeLoaderNamespace {
public:
- NativeLoaderNamespace() : android_ns_(nullptr), native_bridge_ns_(nullptr) {}
-
- explicit NativeLoaderNamespace(android_namespace_t* ns)
- : android_ns_(ns), native_bridge_ns_(nullptr) {}
-
- explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
- : android_ns_(nullptr), native_bridge_ns_(ns) {}
+ // TODO(return with errors)
+ static NativeLoaderNamespace Create(const std::string& name, const std::string& search_paths,
+ const std::string& permitted_paths,
+ const NativeLoaderNamespace* parent, bool is_shared,
+ bool is_greylist_enabled);
NativeLoaderNamespace(NativeLoaderNamespace&&) = default;
NativeLoaderNamespace(const NativeLoaderNamespace&) = default;
NativeLoaderNamespace& operator=(const NativeLoaderNamespace&) = default;
- android_namespace_t* get_android_ns() const {
- CHECK(native_bridge_ns_ == nullptr);
- return android_ns_;
+ android_namespace_t* ToRawAndroidNamespace() const { return std::get<0>(raw_); }
+ native_bridge_namespace_t* ToRawNativeBridgeNamespace() const { return std::get<1>(raw_); }
+
+ std::string name() const { return name_; }
+ bool IsBridged() const { return raw_.index() == 1; }
+ bool IsNil() const {
+ return IsBridged() ? std::get<1>(raw_) == nullptr : std::get<0>(raw_) == nullptr;
}
- native_bridge_namespace_t* get_native_bridge_ns() const {
- CHECK(android_ns_ == nullptr);
- return native_bridge_ns_;
- }
+ bool Link(const NativeLoaderNamespace& target, const std::string& shared_libs) const;
+ void* Load(const char* lib_name) const;
+ char* GetError() const;
- bool is_android_namespace() const { return native_bridge_ns_ == nullptr; }
+ static NativeLoaderNamespace GetExportedNamespace(const std::string& name, bool is_bridged);
+ static NativeLoaderNamespace GetPlatformNamespace(bool is_bridged);
private:
- // Only one of them can be not null
- android_namespace_t* android_ns_;
- native_bridge_namespace_t* native_bridge_ns_;
+ explicit NativeLoaderNamespace(const std::string& name, android_namespace_t* ns)
+ : name_(name), raw_(ns) {}
+ explicit NativeLoaderNamespace(const std::string& name, native_bridge_namespace_t* ns)
+ : name_(name), raw_(ns) {}
+
+ std::string name_;
+ std::variant<android_namespace_t*, native_bridge_namespace_t*> raw_;
};
} // namespace android
diff --git a/libnativeloader/public_libraries.cpp b/libnativeloader/public_libraries.cpp
index 64fedae..c205eb1 100644
--- a/libnativeloader/public_libraries.cpp
+++ b/libnativeloader/public_libraries.cpp
@@ -14,19 +14,21 @@
* limitations under the License.
*/
-#include "public_libraries.h"
#define LOG_TAG "nativeloader"
+#include "public_libraries.h"
+
#include <dirent.h>
#include <algorithm>
#include <memory>
-#include "android-base/file.h"
-#include "android-base/logging.h"
-#include "android-base/properties.h"
-#include "android-base/strings.h"
-#include "log/log.h"
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <log/log.h>
+
#include "utils.h"
namespace android::nativeloader {
diff --git a/libprocessgroup/Android.bp b/libprocessgroup/Android.bp
index 0207a75..52a297c 100644
--- a/libprocessgroup/Android.bp
+++ b/libprocessgroup/Android.bp
@@ -3,6 +3,7 @@
vendor_available: true,
recovery_available: true,
host_supported: true,
+ native_bridge_supported: true,
export_include_dirs: ["include"],
target: {
linux_bionic: {
@@ -25,6 +26,7 @@
host_supported: true,
recovery_available: true,
vendor_available: true,
+ native_bridge_supported: true,
vndk: {
enabled: true,
support_system_process: true,
diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp
index 6cd6b6e..92fcd1e 100644
--- a/libprocessgroup/cgroup_map.cpp
+++ b/libprocessgroup/cgroup_map.cpp
@@ -67,6 +67,13 @@
return controller_ != nullptr;
}
+bool CgroupController::IsUsable() const {
+ if (!HasValue()) return false;
+
+ uint32_t flags = ACgroupController_getFlags(controller_);
+ return (flags & CGROUPRC_CONTROLLER_FLAG_MOUNTED) != 0;
+}
+
std::string CgroupController::GetTasksFilePath(const std::string& rel_path) const {
std::string tasks_path = path();
@@ -153,6 +160,7 @@
const ACgroupController* controller = ACgroupFile_getController(i);
LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
<< ACgroupController_getVersion(controller) << " path "
+ << ACgroupController_getFlags(controller) << " flags "
<< ACgroupController_getPath(controller);
}
}
diff --git a/libprocessgroup/cgroup_map.h b/libprocessgroup/cgroup_map.h
index d765e60..9350412 100644
--- a/libprocessgroup/cgroup_map.h
+++ b/libprocessgroup/cgroup_map.h
@@ -38,6 +38,7 @@
const char* path() const;
bool HasValue() const;
+ bool IsUsable() const;
std::string GetTasksFilePath(const std::string& path) const;
std::string GetProcsFilePath(const std::string& path, uid_t uid, pid_t pid) const;
diff --git a/libprocessgroup/cgrouprc/Android.bp b/libprocessgroup/cgrouprc/Android.bp
index 6848620..0af75bb 100644
--- a/libprocessgroup/cgrouprc/Android.bp
+++ b/libprocessgroup/cgrouprc/Android.bp
@@ -21,6 +21,7 @@
// modules should use libprocessgroup which links to the LL-NDK library
// defined below. The static library is built for tests.
vendor_available: false,
+ native_bridge_supported: true,
srcs: [
"cgroup_controller.cpp",
"cgroup_file.cpp",
@@ -42,19 +43,20 @@
"libcgrouprc_format",
],
stubs: {
- symbol_file: "libcgrouprc.map.txt",
+ symbol_file: "libcgrouprc.llndk.txt",
versions: ["29"],
},
target: {
linux: {
- version_script: "libcgrouprc.map.txt",
+ version_script: "libcgrouprc.llndk.txt",
},
},
}
llndk_library {
name: "libcgrouprc",
- symbol_file: "libcgrouprc.map.txt",
+ symbol_file: "libcgrouprc.llndk.txt",
+ native_bridge_supported: true,
export_include_dirs: [
"include",
],
diff --git a/libprocessgroup/cgrouprc/cgroup_controller.cpp b/libprocessgroup/cgrouprc/cgroup_controller.cpp
index d064d31..5a326e5 100644
--- a/libprocessgroup/cgrouprc/cgroup_controller.cpp
+++ b/libprocessgroup/cgrouprc/cgroup_controller.cpp
@@ -27,6 +27,11 @@
return controller->version();
}
+uint32_t ACgroupController_getFlags(const ACgroupController* controller) {
+ CHECK(controller != nullptr);
+ return controller->flags();
+}
+
const char* ACgroupController_getName(const ACgroupController* controller) {
CHECK(controller != nullptr);
return controller->name();
diff --git a/libprocessgroup/cgrouprc/include/android/cgrouprc.h b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
index 4edd239..ffc9f0b 100644
--- a/libprocessgroup/cgrouprc/include/android/cgrouprc.h
+++ b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
@@ -66,6 +66,18 @@
__INTRODUCED_IN(29);
/**
+ * Flag bitmask used in ACgroupController_getFlags
+ */
+#define CGROUPRC_CONTROLLER_FLAG_MOUNTED 0x1
+
+/**
+ * Returns the flags bitmask of the given controller.
+ * If the given controller is null, return 0.
+ */
+__attribute__((warn_unused_result)) uint32_t ACgroupController_getFlags(const ACgroupController*)
+ __INTRODUCED_IN(29);
+
+/**
* Returns the name of the given controller.
* If the given controller is null, return nullptr.
*/
diff --git a/libprocessgroup/cgrouprc/libcgrouprc.map.txt b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
similarity index 88%
rename from libprocessgroup/cgrouprc/libcgrouprc.map.txt
rename to libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
index 91df392..ea3df33 100644
--- a/libprocessgroup/cgrouprc/libcgrouprc.map.txt
+++ b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
@@ -4,6 +4,7 @@
ACgroupFile_getControllerCount;
ACgroupFile_getController;
ACgroupController_getVersion;
+ ACgroupController_getFlags;
ACgroupController_getName;
ACgroupController_getPath;
local:
diff --git a/libprocessgroup/cgrouprc_format/Android.bp b/libprocessgroup/cgrouprc_format/Android.bp
index dfbeed7..559a869 100644
--- a/libprocessgroup/cgrouprc_format/Android.bp
+++ b/libprocessgroup/cgrouprc_format/Android.bp
@@ -16,6 +16,7 @@
name: "libcgrouprc_format",
host_supported: true,
recovery_available: true,
+ native_bridge_supported: true,
srcs: [
"cgroup_controller.cpp",
],
diff --git a/libprocessgroup/cgrouprc_format/cgroup_controller.cpp b/libprocessgroup/cgrouprc_format/cgroup_controller.cpp
index 877eed8..202b23e 100644
--- a/libprocessgroup/cgrouprc_format/cgroup_controller.cpp
+++ b/libprocessgroup/cgrouprc_format/cgroup_controller.cpp
@@ -20,12 +20,19 @@
namespace cgrouprc {
namespace format {
-CgroupController::CgroupController(uint32_t version, const std::string& name,
- const std::string& path) {
+CgroupController::CgroupController() : version_(0), flags_(0) {
+ memset(name_, 0, sizeof(name_));
+ memset(path_, 0, sizeof(path_));
+}
+
+CgroupController::CgroupController(uint32_t version, uint32_t flags, const std::string& name,
+ const std::string& path)
+ : CgroupController() {
// strlcpy isn't available on host. Although there is an implementation
// in licutils, libcutils itself depends on libcgrouprc_format, causing
// a circular dependency.
version_ = version;
+ flags_ = flags;
strncpy(name_, name.c_str(), sizeof(name_) - 1);
name_[sizeof(name_) - 1] = '\0';
strncpy(path_, path.c_str(), sizeof(path_) - 1);
@@ -36,6 +43,10 @@
return version_;
}
+uint32_t CgroupController::flags() const {
+ return flags_;
+}
+
const char* CgroupController::name() const {
return name_;
}
@@ -44,6 +55,10 @@
return path_;
}
+void CgroupController::set_flags(uint32_t flags) {
+ flags_ = flags;
+}
+
} // namespace format
} // namespace cgrouprc
} // namespace android
diff --git a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h b/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h
index 64c7532..40d8548 100644
--- a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h
+++ b/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h
@@ -26,18 +26,23 @@
// Minimal controller description to be mmapped into process address space
struct CgroupController {
public:
- CgroupController() {}
- CgroupController(uint32_t version, const std::string& name, const std::string& path);
+ CgroupController();
+ CgroupController(uint32_t version, uint32_t flags, const std::string& name,
+ const std::string& path);
uint32_t version() const;
+ uint32_t flags() const;
const char* name() const;
const char* path() const;
+ void set_flags(uint32_t flags);
+
private:
static constexpr size_t CGROUP_NAME_BUF_SZ = 16;
static constexpr size_t CGROUP_PATH_BUF_SZ = 32;
uint32_t version_;
+ uint32_t flags_;
char name_[CGROUP_NAME_BUF_SZ];
char path_[CGROUP_PATH_BUF_SZ];
};
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index 1485ae9..d3ac26b 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -106,8 +106,7 @@
}
static bool isMemoryCgroupSupported() {
- std::string cgroup_name;
- static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").HasValue();
+ static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
return memcg_supported;
}
diff --git a/libprocessgroup/sched_policy.cpp b/libprocessgroup/sched_policy.cpp
index fe4f93b..15f8139 100644
--- a/libprocessgroup/sched_policy.cpp
+++ b/libprocessgroup/sched_policy.cpp
@@ -151,19 +151,19 @@
}
bool cpusets_enabled() {
- static bool enabled = (CgroupMap::GetInstance().FindController("cpuset").HasValue());
+ static bool enabled = (CgroupMap::GetInstance().FindController("cpuset").IsUsable());
return enabled;
}
bool schedboost_enabled() {
- static bool enabled = (CgroupMap::GetInstance().FindController("schedtune").HasValue());
+ static bool enabled = (CgroupMap::GetInstance().FindController("schedtune").IsUsable());
return enabled;
}
static int getCGroupSubsys(int tid, const char* subsys, std::string& subgroup) {
auto controller = CgroupMap::GetInstance().FindController(subsys);
- if (!controller.HasValue()) return -1;
+ if (!controller.IsUsable()) return -1;
if (!controller.GetTaskGroup(tid, &subgroup)) {
LOG(ERROR) << "Failed to find cgroup for tid " << tid;
diff --git a/libprocessgroup/setup/cgroup_descriptor.h b/libprocessgroup/setup/cgroup_descriptor.h
index 597060e..f029c4f 100644
--- a/libprocessgroup/setup/cgroup_descriptor.h
+++ b/libprocessgroup/setup/cgroup_descriptor.h
@@ -32,6 +32,8 @@
std::string uid() const { return uid_; }
std::string gid() const { return gid_; }
+ void set_mounted(bool mounted);
+
private:
format::CgroupController controller_;
mode_t mode_ = 0;
diff --git a/libprocessgroup/setup/cgroup_map_write.cpp b/libprocessgroup/setup/cgroup_map_write.cpp
index da60948..17ea06e 100644
--- a/libprocessgroup/setup/cgroup_map_write.cpp
+++ b/libprocessgroup/setup/cgroup_map_write.cpp
@@ -35,6 +35,7 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/unique_fd.h>
+#include <android/cgrouprc.h>
#include <json/reader.h>
#include <json/value.h>
#include <processgroup/format/cgroup_file.h>
@@ -267,7 +268,17 @@
CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
const std::string& path, mode_t mode, const std::string& uid,
const std::string& gid)
- : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
+ : controller_(version, 0, name, path), mode_(mode), uid_(uid), gid_(gid) {}
+
+void CgroupDescriptor::set_mounted(bool mounted) {
+ uint32_t flags = controller_.flags();
+ if (mounted) {
+ flags |= CGROUPRC_CONTROLLER_FLAG_MOUNTED;
+ } else {
+ flags &= ~CGROUPRC_CONTROLLER_FLAG_MOUNTED;
+ }
+ controller_.set_flags(flags);
+}
} // namespace cgrouprc
} // namespace android
@@ -296,10 +307,11 @@
}
// setup cgroups
- for (const auto& [name, descriptor] : descriptors) {
- if (!SetupCgroup(descriptor)) {
+ for (auto& [name, descriptor] : descriptors) {
+ if (SetupCgroup(descriptor)) {
+ descriptor.set_mounted(true);
+ } else {
// issue a warning and proceed with the next cgroup
- // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
LOG(WARNING) << "Failed to setup " << name << " cgroup";
}
}
diff --git a/libsystem/Android.bp b/libsystem/Android.bp
index 2e22b43..b265b61 100644
--- a/libsystem/Android.bp
+++ b/libsystem/Android.bp
@@ -3,6 +3,7 @@
vendor_available: true,
recovery_available: true,
host_supported: true,
+ native_bridge_supported: true,
export_include_dirs: ["include"],
target: {
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 4f194c7..8be4dd0 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -17,6 +17,7 @@
vendor_available: true,
recovery_available: true,
host_supported: true,
+ native_bridge_supported: true,
header_libs: [
"liblog_headers",
@@ -121,6 +122,7 @@
cc_library {
name: "libutils",
defaults: ["libutils_defaults"],
+ native_bridge_supported: true,
srcs: [
"FileMap.cpp",
diff --git a/libvndksupport/Android.bp b/libvndksupport/Android.bp
index 546c15c..e5b536c 100644
--- a/libvndksupport/Android.bp
+++ b/libvndksupport/Android.bp
@@ -2,6 +2,7 @@
cc_library {
name: "libvndksupport",
+ native_bridge_supported: true,
srcs: ["linker.c"],
cflags: [
"-Wall",
@@ -22,6 +23,7 @@
llndk_library {
name: "libvndksupport",
+ native_bridge_supported: true,
symbol_file: "libvndksupport.map.txt",
export_include_dirs: ["include"],
}
diff --git a/libziparchive/include/ziparchive/zip_archive.h b/libziparchive/include/ziparchive/zip_archive.h
index 7eead7e..a56a4a2 100644
--- a/libziparchive/include/ziparchive/zip_archive.h
+++ b/libziparchive/include/ziparchive/zip_archive.h
@@ -25,6 +25,7 @@
#include <sys/cdefs.h>
#include <sys/types.h>
+#include <string>
#include <string_view>
#include "android-base/off64_t.h"
@@ -35,6 +36,7 @@
kCompressDeflated = 8, // standard deflate
};
+// TODO: remove this when everyone's moved over to std::string.
struct ZipString {
const uint8_t* name;
uint16_t name_length;
@@ -180,9 +182,6 @@
int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
const std::string_view optional_prefix = "",
const std::string_view optional_suffix = "");
-// TODO: remove this.
-int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
- const ZipString* optional_prefix, const ZipString* optional_suffix);
/*
* Advance to the next element in the zipfile in iteration order.
@@ -190,6 +189,8 @@
* Returns 0 on success, -1 if there are no more elements in this
* archive and lower negative values on failure.
*/
+int32_t Next(void* cookie, ZipEntry* data, std::string* name);
+// TODO: remove this when everyone's moved over to std::string.
int32_t Next(void* cookie, ZipEntry* data, ZipString* name);
/*
diff --git a/libziparchive/unzip.cpp b/libziparchive/unzip.cpp
index 3a3a694..426325e 100644
--- a/libziparchive/unzip.cpp
+++ b/libziparchive/unzip.cpp
@@ -255,9 +255,8 @@
}
ZipEntry entry;
- ZipString string;
- while ((err = Next(cookie, &entry, &string)) >= 0) {
- std::string name(string.name, string.name + string.name_length);
+ std::string name;
+ while ((err = Next(cookie, &entry, &name)) >= 0) {
if (ShouldInclude(name)) ProcessOne(zah, entry, name);
}
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index ac3e236..f4b6c74 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -726,22 +726,6 @@
return 0;
}
-// TODO: remove this.
-int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
- const ZipString* optional_prefix, const ZipString* optional_suffix) {
- std::string prefix;
- if (optional_prefix) {
- prefix = std::string(reinterpret_cast<const char*>(optional_prefix->name),
- optional_prefix->name_length);
- }
- std::string suffix;
- if (optional_suffix) {
- suffix = std::string(reinterpret_cast<const char*>(optional_suffix->name),
- optional_suffix->name_length);
- }
- return StartIteration(archive, cookie_ptr, prefix.c_str(), suffix.c_str());
-}
-
void EndIteration(void* cookie) {
delete reinterpret_cast<IterationHandle*>(cookie);
}
@@ -763,6 +747,15 @@
return FindEntry(archive, static_cast<uint32_t>(ent), data);
}
+int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
+ ZipString zs;
+ int32_t result = Next(cookie, data, &zs);
+ if (result == 0) {
+ *name = std::string(reinterpret_cast<const char*>(zs.name), zs.name_length);
+ }
+ return result;
+}
+
int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
if (handle == NULL) {
diff --git a/libziparchive/zip_archive_benchmark.cpp b/libziparchive/zip_archive_benchmark.cpp
index 434f2e1..23ed408 100644
--- a/libziparchive/zip_archive_benchmark.cpp
+++ b/libziparchive/zip_archive_benchmark.cpp
@@ -71,7 +71,7 @@
ZipArchiveHandle handle;
void* iteration_cookie;
ZipEntry data;
- ZipString name;
+ std::string name;
while (state.KeepRunning()) {
OpenArchive(temp_file->path, &handle);
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index 993c975..b6ca9ec 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -118,10 +118,10 @@
ZipEntry data;
std::vector<std::string> names;
- ZipString name;
+ std::string 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));
+ names.push_back(name);
}
// End of iteration.
@@ -167,7 +167,7 @@
ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, "x", "y"));
ZipEntry data;
- ZipString name;
+ std::string name;
// End of iteration.
ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
@@ -224,7 +224,7 @@
void* iteration_cookie;
ASSERT_EQ(0, StartIteration(handle, &iteration_cookie));
- ZipString name;
+ std::string name;
ZipEntry data;
ASSERT_EQ(Next(iteration_cookie, &data, &name), 0);
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index 07040b0..25104eb 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -4,10 +4,15 @@
# Make sure any property changes are only performed with /data mounted, after
# post-fs-data state because otherwise behavior is undefined. The exceptions
# are device adjustments for logcatd service properties (persist.* overrides
-# notwithstanding) for logd.logpersistd.size and logd.logpersistd.buffer.
+# notwithstanding) for logd.logpersistd.size logd.logpersistd.rotate_kbytes and
+# logd.logpersistd.buffer.
# persist to non-persistent trampolines to permit device properties can be
# overridden when /data mounts, or during runtime.
+on property:persist.logd.logpersistd.count=*
+ # expect /init to report failure if property empty (default)
+ setprop persist.logd.logpersistd.size ${persist.logd.logpersistd.count}
+
on property:persist.logd.logpersistd.size=256
setprop persist.logd.logpersistd.size ""
setprop logd.logpersistd.size ""
@@ -16,6 +21,14 @@
# expect /init to report failure if property empty (default)
setprop logd.logpersistd.size ${persist.logd.logpersistd.size}
+on property:persist.logd.logpersistd.rotate_kbytes=1024
+ setprop persist.logd.logpersistd.rotate_kbytes ""
+ setprop logd.logpersistd.rotate_kbytes ""
+
+on property:persist.logd.logpersistd.rotate_kbytes=*
+ # expect /init to report failure if property empty (default)
+ setprop logd.logpersistd.rotate_kbytes ${persist.logd.logpersistd.rotate_kbytes}
+
on property:persist.logd.logpersistd.buffer=all
setprop persist.logd.logpersistd.buffer ""
setprop logd.logpersistd.buffer ""
@@ -54,7 +67,7 @@
stop logcatd
# logcatd service
-service logcatd /system/bin/logcatd -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
+service logcatd /system/bin/logcatd -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r ${logd.logpersistd.rotate_kbytes:-1024} -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
class late_start
disabled
# logd for write to /data/misc/logd, log group for read from log daemon
diff --git a/logd/README.property b/logd/README.property
index da5f96f..d2a2cbb 100644
--- a/logd/README.property
+++ b/logd/README.property
@@ -17,10 +17,13 @@
Responds to logcatd, clear and stop.
logd.logpersistd.buffer persist logpersistd buffers to collect
logd.logpersistd.size persist logpersistd size in MB
+logd.logpersistd.rotate_kbytes persist logpersistd outout file size in KB.
persist.logd.logpersistd string Enable logpersist daemon, "logcatd"
turns on logcat -f in logd context.
persist.logd.logpersistd.buffer all logpersistd buffers to collect
persist.logd.logpersistd.size 256 logpersistd size in MB
+persist.logd.logpersistd.count 256 sets max number of rotated logs to <count>.
+persist.logd.logpersistd.rotate_kbytes 1024 logpersistd output file size in KB
persist.logd.size number ro Global default size of the buffer for
all log ids at initial startup, at
runtime use: logcat -b all -G <value>
diff --git a/mkbootimg/mkbootimg.py b/mkbootimg/mkbootimg.py
index 92b11a5..934f28e 100644
--- a/mkbootimg/mkbootimg.py
+++ b/mkbootimg/mkbootimg.py
@@ -113,6 +113,10 @@
args.output.write(pack('I', BOOT_IMAGE_HEADER_V2_SIZE))
if args.header_version > 1:
+
+ if filesize(args.dtb) == 0:
+ raise ValueError("DTB image must not be empty.")
+
args.output.write(pack('I', filesize(args.dtb))) # size in bytes
args.output.write(pack('Q', args.base + args.dtb_offset)) # dtb physical load address
pad_file(args.output, args.pagesize)
diff --git a/rootdir/etc/ld.config.legacy.txt b/rootdir/etc/ld.config.legacy.txt
index 4b07478..f6b5e95 100644
--- a/rootdir/etc/ld.config.legacy.txt
+++ b/rootdir/etc/ld.config.legacy.txt
@@ -56,6 +56,9 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index f4710d8..6c4f8ab 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -135,12 +135,16 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
# TODO(b/122876336): Remove libpac.so once it's migrated to Webview
namespace.default.link.runtime.shared_libs += libpac.so
+namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
# When libnetd_resolv.so can't be found in the default namespace, search for it
# in the resolv namespace. Don't allow any other libraries from the resolv namespace
@@ -367,7 +371,7 @@
# The "vndk" namespace links to "default" namespace for LLNDK libs and links to
# "sphal" namespace for vendor libs. The ordering matters. The "default"
# namespace has higher priority than the "sphal" namespace.
-namespace.vndk.links = default,sphal
+namespace.vndk.links = default,sphal,runtime
# When these NDK libs are required inside this namespace, then it is redirected
# to the default namespace. This is possible since their ABI is stable across
@@ -375,6 +379,8 @@
namespace.vndk.link.default.shared_libs = %LLNDK_LIBRARIES%
namespace.vndk.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
+namespace.vndk.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
+
# Allow VNDK-SP extensions to use vendor libraries
namespace.vndk.link.sphal.allow_all_shared_libs = true
@@ -427,8 +433,10 @@
namespace.default.asan.permitted.paths += /data/asan/vendor
namespace.default.asan.permitted.paths += /vendor
-namespace.default.links = system,vndk%VNDK_IN_SYSTEM_NS%
-namespace.default.link.system.shared_libs = %LLNDK_LIBRARIES%
+namespace.default.links = system,vndk%VNDK_IN_SYSTEM_NS%,runtime
+namespace.default.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
+namespace.default.link.system.shared_libs = %LLNDK_LIBRARIES%
+namespace.default.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
namespace.default.link.vndk_in_system.shared_libs = %VNDK_USING_CORE_VARIANT_LIBRARIES%
namespace.default.link.vndk.shared_libs = %VNDK_SAMEPROCESS_LIBRARIES%
namespace.default.link.vndk.shared_libs += %VNDK_CORE_LIBRARIES%
@@ -481,13 +489,15 @@
# Android releases. The links here should be identical to that of the
# 'vndk_in_system' namespace, except for the link between 'vndk' and
# 'vndk_in_system'.
-namespace.vndk.links = system,default%VNDK_IN_SYSTEM_NS%
+namespace.vndk.links = system,default%VNDK_IN_SYSTEM_NS%,runtime
namespace.vndk.link.system.shared_libs = %LLNDK_LIBRARIES%
namespace.vndk.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
namespace.vndk.link.default.allow_all_shared_libs = true
+namespace.vndk.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
+
namespace.vndk.link.vndk_in_system.shared_libs = %VNDK_USING_CORE_VARIANT_LIBRARIES%
###############################################################################
@@ -512,11 +522,15 @@
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
+namespace.system.link.runtime.shared_libs += libicui18n.so
+namespace.system.link.runtime.shared_libs += libicuuc.so
namespace.system.link.runtime.shared_libs += libnativebridge.so
namespace.system.link.runtime.shared_libs += libnativehelper.so
namespace.system.link.runtime.shared_libs += libnativeloader.so
# Workaround for b/124772622
namespace.system.link.runtime.shared_libs += libandroidicu.so
+namespace.system.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
###############################################################################
# "vndk_in_system" namespace
@@ -555,7 +569,8 @@
# 1. 'vndk_in_system' needs to be freely linked back to 'vndk'.
# 2. 'vndk_in_system' does not need to link to 'default', as any library that
# requires anything vendor would not be a vndk_in_system library.
-namespace.vndk_in_system.links = vndk,system
+namespace.vndk_in_system.links = vndk,system,runtime
+namespace.vndk_in_system.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
namespace.vndk_in_system.link.system.shared_libs = %LLNDK_LIBRARIES%
namespace.vndk_in_system.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
@@ -592,6 +607,9 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
@@ -687,3 +705,5 @@
namespace.default.search.paths = /system/${LIB}
namespace.default.search.paths += /%PRODUCT%/${LIB}
namespace.default.search.paths += /%PRODUCT_SERVICES%/${LIB}
+
+namespace.default.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
diff --git a/rootdir/etc/ld.config.vndk_lite.txt b/rootdir/etc/ld.config.vndk_lite.txt
index 4ce7f52..d616582 100644
--- a/rootdir/etc/ld.config.vndk_lite.txt
+++ b/rootdir/etc/ld.config.vndk_lite.txt
@@ -75,6 +75,9 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
@@ -363,6 +366,9 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
@@ -413,6 +419,9 @@
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
+namespace.default.link.runtime.shared_libs += libicui18n.so
+namespace.default.link.runtime.shared_libs += libicuuc.so
namespace.default.link.runtime.shared_libs += libnativebridge.so
namespace.default.link.runtime.shared_libs += libnativehelper.so
namespace.default.link.runtime.shared_libs += libnativeloader.so
diff --git a/trusty/keymaster/4.0/TrustyKeymaster4Device.cpp b/trusty/keymaster/4.0/TrustyKeymaster4Device.cpp
new file mode 100644
index 0000000..b5fc6bf
--- /dev/null
+++ b/trusty/keymaster/4.0/TrustyKeymaster4Device.cpp
@@ -0,0 +1,571 @@
+/*
+ **
+ ** Copyright 2018, 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 LOG_TAG "android.hardware.keymaster@4.0-impl.trusty"
+
+#include <authorization_set.h>
+#include <cutils/log.h>
+#include <keymaster/android_keymaster_messages.h>
+#include <trusty_keymaster/TrustyKeymaster4Device.h>
+#include <trusty_keymaster/ipc/trusty_keymaster_ipc.h>
+
+using ::keymaster::AbortOperationRequest;
+using ::keymaster::AbortOperationResponse;
+using ::keymaster::AddEntropyRequest;
+using ::keymaster::AddEntropyResponse;
+using ::keymaster::AttestKeyRequest;
+using ::keymaster::AttestKeyResponse;
+using ::keymaster::AuthorizationSet;
+using ::keymaster::BeginOperationRequest;
+using ::keymaster::BeginOperationResponse;
+using ::keymaster::ExportKeyRequest;
+using ::keymaster::ExportKeyResponse;
+using ::keymaster::FinishOperationRequest;
+using ::keymaster::FinishOperationResponse;
+using ::keymaster::GenerateKeyRequest;
+using ::keymaster::GenerateKeyResponse;
+using ::keymaster::GetKeyCharacteristicsRequest;
+using ::keymaster::GetKeyCharacteristicsResponse;
+using ::keymaster::ImportKeyRequest;
+using ::keymaster::ImportKeyResponse;
+using ::keymaster::UpdateOperationRequest;
+using ::keymaster::UpdateOperationResponse;
+using ::keymaster::ng::Tag;
+
+namespace keymaster {
+namespace V4_0 {
+namespace {
+
+inline keymaster_tag_t legacy_enum_conversion(const Tag value) {
+ return keymaster_tag_t(value);
+}
+inline Tag legacy_enum_conversion(const keymaster_tag_t value) {
+ return Tag(value);
+}
+inline keymaster_purpose_t legacy_enum_conversion(const KeyPurpose value) {
+ return keymaster_purpose_t(value);
+}
+inline keymaster_key_format_t legacy_enum_conversion(const KeyFormat value) {
+ return keymaster_key_format_t(value);
+}
+
+inline SecurityLevel legacy_enum_conversion(const keymaster_security_level_t value) {
+ return static_cast<SecurityLevel>(value);
+}
+
+inline hw_authenticator_type_t legacy_enum_conversion(const HardwareAuthenticatorType value) {
+ return static_cast<hw_authenticator_type_t>(value);
+}
+
+inline ErrorCode legacy_enum_conversion(const keymaster_error_t value) {
+ return ErrorCode(value);
+}
+
+inline keymaster_tag_type_t typeFromTag(const keymaster_tag_t tag) {
+ return keymaster_tag_get_type(tag);
+}
+
+class KmParamSet : public keymaster_key_param_set_t {
+ public:
+ KmParamSet(const hidl_vec<KeyParameter>& keyParams) {
+ params = new keymaster_key_param_t[keyParams.size()];
+ length = keyParams.size();
+ for (size_t i = 0; i < keyParams.size(); ++i) {
+ auto tag = legacy_enum_conversion(keyParams[i].tag);
+ switch (typeFromTag(tag)) {
+ case KM_ENUM:
+ case KM_ENUM_REP:
+ params[i] = keymaster_param_enum(tag, keyParams[i].f.integer);
+ break;
+ case KM_UINT:
+ case KM_UINT_REP:
+ params[i] = keymaster_param_int(tag, keyParams[i].f.integer);
+ break;
+ case KM_ULONG:
+ case KM_ULONG_REP:
+ params[i] = keymaster_param_long(tag, keyParams[i].f.longInteger);
+ break;
+ case KM_DATE:
+ params[i] = keymaster_param_date(tag, keyParams[i].f.dateTime);
+ break;
+ case KM_BOOL:
+ if (keyParams[i].f.boolValue)
+ params[i] = keymaster_param_bool(tag);
+ else
+ params[i].tag = KM_TAG_INVALID;
+ break;
+ case KM_BIGNUM:
+ case KM_BYTES:
+ params[i] = keymaster_param_blob(tag, &keyParams[i].blob[0],
+ keyParams[i].blob.size());
+ break;
+ case KM_INVALID:
+ default:
+ params[i].tag = KM_TAG_INVALID;
+ /* just skip */
+ break;
+ }
+ }
+ }
+ KmParamSet(KmParamSet&& other) noexcept
+ : keymaster_key_param_set_t{other.params, other.length} {
+ other.length = 0;
+ other.params = nullptr;
+ }
+ KmParamSet(const KmParamSet&) = delete;
+ ~KmParamSet() { delete[] params; }
+};
+
+inline hidl_vec<uint8_t> kmBlob2hidlVec(const keymaster_key_blob_t& blob) {
+ hidl_vec<uint8_t> result;
+ result.setToExternal(const_cast<unsigned char*>(blob.key_material), blob.key_material_size);
+ return result;
+}
+
+inline hidl_vec<uint8_t> kmBlob2hidlVec(const keymaster_blob_t& blob) {
+ hidl_vec<uint8_t> result;
+ result.setToExternal(const_cast<unsigned char*>(blob.data), blob.data_length);
+ return result;
+}
+
+inline hidl_vec<uint8_t> kmBuffer2hidlVec(const ::keymaster::Buffer& buf) {
+ hidl_vec<uint8_t> result;
+ result.setToExternal(const_cast<unsigned char*>(buf.peek_read()), buf.available_read());
+ return result;
+}
+
+inline static hidl_vec<hidl_vec<uint8_t>> kmCertChain2Hidl(
+ const keymaster_cert_chain_t& cert_chain) {
+ hidl_vec<hidl_vec<uint8_t>> result;
+ if (!cert_chain.entry_count || !cert_chain.entries) return result;
+
+ result.resize(cert_chain.entry_count);
+ for (size_t i = 0; i < cert_chain.entry_count; ++i) {
+ result[i] = kmBlob2hidlVec(cert_chain.entries[i]);
+ }
+
+ return result;
+}
+
+static inline hidl_vec<KeyParameter> kmParamSet2Hidl(const keymaster_key_param_set_t& set) {
+ hidl_vec<KeyParameter> result;
+ if (set.length == 0 || set.params == nullptr) return result;
+
+ result.resize(set.length);
+ keymaster_key_param_t* params = set.params;
+ for (size_t i = 0; i < set.length; ++i) {
+ auto tag = params[i].tag;
+ result[i].tag = legacy_enum_conversion(tag);
+ switch (typeFromTag(tag)) {
+ case KM_ENUM:
+ case KM_ENUM_REP:
+ result[i].f.integer = params[i].enumerated;
+ break;
+ case KM_UINT:
+ case KM_UINT_REP:
+ result[i].f.integer = params[i].integer;
+ break;
+ case KM_ULONG:
+ case KM_ULONG_REP:
+ result[i].f.longInteger = params[i].long_integer;
+ break;
+ case KM_DATE:
+ result[i].f.dateTime = params[i].date_time;
+ break;
+ case KM_BOOL:
+ result[i].f.boolValue = params[i].boolean;
+ break;
+ case KM_BIGNUM:
+ case KM_BYTES:
+ result[i].blob.setToExternal(const_cast<unsigned char*>(params[i].blob.data),
+ params[i].blob.data_length);
+ break;
+ case KM_INVALID:
+ default:
+ params[i].tag = KM_TAG_INVALID;
+ /* just skip */
+ break;
+ }
+ }
+ return result;
+}
+
+void addClientAndAppData(const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
+ ::keymaster::AuthorizationSet* params) {
+ params->Clear();
+ if (clientId.size()) {
+ params->push_back(::keymaster::TAG_APPLICATION_ID, clientId.data(), clientId.size());
+ }
+ if (appData.size()) {
+ params->push_back(::keymaster::TAG_APPLICATION_DATA, appData.data(), appData.size());
+ }
+}
+
+} // anonymous namespace
+
+TrustyKeymaster4Device::TrustyKeymaster4Device(TrustyKeymaster* impl) : impl_(impl) {}
+
+TrustyKeymaster4Device::~TrustyKeymaster4Device() {}
+
+Return<void> TrustyKeymaster4Device::getHardwareInfo(getHardwareInfo_cb _hidl_cb) {
+ _hidl_cb(SecurityLevel::TRUSTED_ENVIRONMENT, "TrustyKeymaster", "Google");
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::getHmacSharingParameters(
+ getHmacSharingParameters_cb _hidl_cb) {
+ const GetHmacSharingParametersResponse response = impl_->GetHmacSharingParameters();
+ // response.params is not the same as the HIDL structure, we need to convert it
+ V4_0::HmacSharingParameters params;
+ params.seed.setToExternal(const_cast<uint8_t*>(response.params.seed.data),
+ response.params.seed.data_length);
+ static_assert(sizeof(response.params.nonce) == params.nonce.size(), "Nonce sizes don't match");
+ memcpy(params.nonce.data(), response.params.nonce, params.nonce.size());
+ _hidl_cb(legacy_enum_conversion(response.error), params);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::computeSharedHmac(
+ const hidl_vec<HmacSharingParameters>& params, computeSharedHmac_cb _hidl_cb) {
+ ComputeSharedHmacRequest request;
+ request.params_array.params_array = new keymaster::HmacSharingParameters[params.size()];
+ request.params_array.num_params = params.size();
+ for (size_t i = 0; i < params.size(); ++i) {
+ request.params_array.params_array[i].seed = {params[i].seed.data(), params[i].seed.size()};
+ static_assert(sizeof(request.params_array.params_array[i].nonce) ==
+ decltype(params[i].nonce)::size(),
+ "Nonce sizes don't match");
+ memcpy(request.params_array.params_array[i].nonce, params[i].nonce.data(),
+ params[i].nonce.size());
+ }
+
+ auto response = impl_->ComputeSharedHmac(request);
+ hidl_vec<uint8_t> sharing_check;
+ if (response.error == KM_ERROR_OK) {
+ sharing_check = kmBlob2hidlVec(response.sharing_check);
+ }
+
+ _hidl_cb(legacy_enum_conversion(response.error), sharing_check);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::verifyAuthorization(
+ uint64_t challenge, const hidl_vec<KeyParameter>& parametersToVerify,
+ const HardwareAuthToken& authToken, verifyAuthorization_cb _hidl_cb) {
+ VerifyAuthorizationRequest request;
+ request.challenge = challenge;
+ request.parameters_to_verify.Reinitialize(KmParamSet(parametersToVerify));
+ request.auth_token.challenge = authToken.challenge;
+ request.auth_token.user_id = authToken.userId;
+ request.auth_token.authenticator_id = authToken.authenticatorId;
+ request.auth_token.authenticator_type = legacy_enum_conversion(authToken.authenticatorType);
+ request.auth_token.timestamp = authToken.timestamp;
+ KeymasterBlob mac(authToken.mac.data(), authToken.mac.size());
+ request.auth_token.mac = mac;
+
+ auto response = impl_->VerifyAuthorization(request);
+
+ ::android::hardware::keymaster::V4_0::VerificationToken token;
+ token.challenge = response.token.challenge;
+ token.timestamp = response.token.timestamp;
+ token.parametersVerified = kmParamSet2Hidl(response.token.parameters_verified);
+ token.securityLevel = legacy_enum_conversion(response.token.security_level);
+ token.mac = kmBlob2hidlVec(response.token.mac);
+
+ _hidl_cb(legacy_enum_conversion(response.error), token);
+
+ return Void();
+}
+
+Return<ErrorCode> TrustyKeymaster4Device::addRngEntropy(const hidl_vec<uint8_t>& data) {
+ if (data.size() == 0) return ErrorCode::OK;
+ AddEntropyRequest request;
+ request.random_data.Reinitialize(data.data(), data.size());
+
+ AddEntropyResponse response;
+ impl_->AddRngEntropy(request, &response);
+
+ return legacy_enum_conversion(response.error);
+}
+
+Return<void> TrustyKeymaster4Device::generateKey(const hidl_vec<KeyParameter>& keyParams,
+ generateKey_cb _hidl_cb) {
+ GenerateKeyRequest request;
+ request.key_description.Reinitialize(KmParamSet(keyParams));
+
+ GenerateKeyResponse response;
+ impl_->GenerateKey(request, &response);
+
+ KeyCharacteristics resultCharacteristics;
+ hidl_vec<uint8_t> resultKeyBlob;
+ if (response.error == KM_ERROR_OK) {
+ resultKeyBlob = kmBlob2hidlVec(response.key_blob);
+ resultCharacteristics.hardwareEnforced = kmParamSet2Hidl(response.enforced);
+ resultCharacteristics.softwareEnforced = kmParamSet2Hidl(response.unenforced);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultKeyBlob, resultCharacteristics);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::getKeyCharacteristics(const hidl_vec<uint8_t>& keyBlob,
+ const hidl_vec<uint8_t>& clientId,
+ const hidl_vec<uint8_t>& appData,
+ getKeyCharacteristics_cb _hidl_cb) {
+ GetKeyCharacteristicsRequest request;
+ request.SetKeyMaterial(keyBlob.data(), keyBlob.size());
+ addClientAndAppData(clientId, appData, &request.additional_params);
+
+ GetKeyCharacteristicsResponse response;
+ impl_->GetKeyCharacteristics(request, &response);
+
+ KeyCharacteristics resultCharacteristics;
+ if (response.error == KM_ERROR_OK) {
+ resultCharacteristics.hardwareEnforced = kmParamSet2Hidl(response.enforced);
+ resultCharacteristics.softwareEnforced = kmParamSet2Hidl(response.unenforced);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultCharacteristics);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::importKey(const hidl_vec<KeyParameter>& params,
+ KeyFormat keyFormat,
+ const hidl_vec<uint8_t>& keyData,
+ importKey_cb _hidl_cb) {
+ ImportKeyRequest request;
+ request.key_description.Reinitialize(KmParamSet(params));
+ request.key_format = legacy_enum_conversion(keyFormat);
+ request.SetKeyMaterial(keyData.data(), keyData.size());
+
+ ImportKeyResponse response;
+ impl_->ImportKey(request, &response);
+
+ KeyCharacteristics resultCharacteristics;
+ hidl_vec<uint8_t> resultKeyBlob;
+ if (response.error == KM_ERROR_OK) {
+ resultKeyBlob = kmBlob2hidlVec(response.key_blob);
+ resultCharacteristics.hardwareEnforced = kmParamSet2Hidl(response.enforced);
+ resultCharacteristics.softwareEnforced = kmParamSet2Hidl(response.unenforced);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultKeyBlob, resultCharacteristics);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::importWrappedKey(
+ const hidl_vec<uint8_t>& wrappedKeyData, const hidl_vec<uint8_t>& wrappingKeyBlob,
+ const hidl_vec<uint8_t>& maskingKey, const hidl_vec<KeyParameter>& unwrappingParams,
+ uint64_t passwordSid, uint64_t biometricSid, importWrappedKey_cb _hidl_cb) {
+ ImportWrappedKeyRequest request;
+ request.SetWrappedMaterial(wrappedKeyData.data(), wrappedKeyData.size());
+ request.SetWrappingMaterial(wrappingKeyBlob.data(), wrappingKeyBlob.size());
+ request.SetMaskingKeyMaterial(maskingKey.data(), maskingKey.size());
+ request.additional_params.Reinitialize(KmParamSet(unwrappingParams));
+ request.password_sid = passwordSid;
+ request.biometric_sid = biometricSid;
+
+ ImportWrappedKeyResponse response;
+ impl_->ImportWrappedKey(request, &response);
+
+ KeyCharacteristics resultCharacteristics;
+ hidl_vec<uint8_t> resultKeyBlob;
+ if (response.error == KM_ERROR_OK) {
+ resultKeyBlob = kmBlob2hidlVec(response.key_blob);
+ resultCharacteristics.hardwareEnforced = kmParamSet2Hidl(response.enforced);
+ resultCharacteristics.softwareEnforced = kmParamSet2Hidl(response.unenforced);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultKeyBlob, resultCharacteristics);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::exportKey(KeyFormat exportFormat,
+ const hidl_vec<uint8_t>& keyBlob,
+ const hidl_vec<uint8_t>& clientId,
+ const hidl_vec<uint8_t>& appData,
+ exportKey_cb _hidl_cb) {
+ ExportKeyRequest request;
+ request.key_format = legacy_enum_conversion(exportFormat);
+ request.SetKeyMaterial(keyBlob.data(), keyBlob.size());
+ addClientAndAppData(clientId, appData, &request.additional_params);
+
+ ExportKeyResponse response;
+ impl_->ExportKey(request, &response);
+
+ hidl_vec<uint8_t> resultKeyBlob;
+ if (response.error == KM_ERROR_OK) {
+ resultKeyBlob.setToExternal(response.key_data, response.key_data_length);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultKeyBlob);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::attestKey(const hidl_vec<uint8_t>& keyToAttest,
+ const hidl_vec<KeyParameter>& attestParams,
+ attestKey_cb _hidl_cb) {
+ AttestKeyRequest request;
+ request.SetKeyMaterial(keyToAttest.data(), keyToAttest.size());
+ request.attest_params.Reinitialize(KmParamSet(attestParams));
+
+ AttestKeyResponse response;
+ impl_->AttestKey(request, &response);
+
+ hidl_vec<hidl_vec<uint8_t>> resultCertChain;
+ if (response.error == KM_ERROR_OK) {
+ resultCertChain = kmCertChain2Hidl(response.certificate_chain);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultCertChain);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::upgradeKey(const hidl_vec<uint8_t>& keyBlobToUpgrade,
+ const hidl_vec<KeyParameter>& upgradeParams,
+ upgradeKey_cb _hidl_cb) {
+ UpgradeKeyRequest request;
+ request.SetKeyMaterial(keyBlobToUpgrade.data(), keyBlobToUpgrade.size());
+ request.upgrade_params.Reinitialize(KmParamSet(upgradeParams));
+
+ UpgradeKeyResponse response;
+ impl_->UpgradeKey(request, &response);
+
+ if (response.error == KM_ERROR_OK) {
+ _hidl_cb(ErrorCode::OK, kmBlob2hidlVec(response.upgraded_key));
+ } else {
+ _hidl_cb(legacy_enum_conversion(response.error), hidl_vec<uint8_t>());
+ }
+ return Void();
+}
+
+Return<ErrorCode> TrustyKeymaster4Device::deleteKey(const hidl_vec<uint8_t>& keyBlob) {
+ DeleteKeyRequest request;
+ request.SetKeyMaterial(keyBlob.data(), keyBlob.size());
+
+ DeleteKeyResponse response;
+ impl_->DeleteKey(request, &response);
+
+ return legacy_enum_conversion(response.error);
+}
+
+Return<ErrorCode> TrustyKeymaster4Device::deleteAllKeys() {
+ DeleteAllKeysRequest request;
+ DeleteAllKeysResponse response;
+ impl_->DeleteAllKeys(request, &response);
+
+ return legacy_enum_conversion(response.error);
+}
+
+Return<ErrorCode> TrustyKeymaster4Device::destroyAttestationIds() {
+ return ErrorCode::UNIMPLEMENTED;
+}
+
+Return<void> TrustyKeymaster4Device::begin(KeyPurpose purpose, const hidl_vec<uint8_t>& key,
+ const hidl_vec<KeyParameter>& inParams,
+ const HardwareAuthToken& authToken, begin_cb _hidl_cb) {
+ (void)authToken;
+ BeginOperationRequest request;
+ request.purpose = legacy_enum_conversion(purpose);
+ request.SetKeyMaterial(key.data(), key.size());
+ request.additional_params.Reinitialize(KmParamSet(inParams));
+
+ BeginOperationResponse response;
+ impl_->BeginOperation(request, &response);
+
+ hidl_vec<KeyParameter> resultParams;
+ if (response.error == KM_ERROR_OK) {
+ resultParams = kmParamSet2Hidl(response.output_params);
+ }
+
+ _hidl_cb(legacy_enum_conversion(response.error), resultParams, response.op_handle);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::update(uint64_t operationHandle,
+ const hidl_vec<KeyParameter>& inParams,
+ const hidl_vec<uint8_t>& input,
+ const HardwareAuthToken& authToken,
+ const VerificationToken& verificationToken,
+ update_cb _hidl_cb) {
+ (void)authToken;
+ (void)verificationToken;
+ UpdateOperationRequest request;
+ UpdateOperationResponse response;
+ hidl_vec<KeyParameter> resultParams;
+ hidl_vec<uint8_t> resultBlob;
+ uint32_t resultConsumed = 0;
+
+ request.op_handle = operationHandle;
+ request.additional_params.Reinitialize(KmParamSet(inParams));
+
+ size_t inp_size = input.size();
+ size_t ser_size = request.SerializedSize();
+
+ if (ser_size > TRUSTY_KEYMASTER_SEND_BUF_SIZE) {
+ response.error = KM_ERROR_INVALID_INPUT_LENGTH;
+ } else {
+ if (ser_size + inp_size > TRUSTY_KEYMASTER_SEND_BUF_SIZE) {
+ inp_size = TRUSTY_KEYMASTER_SEND_BUF_SIZE - ser_size;
+ }
+ request.input.Reinitialize(input.data(), inp_size);
+
+ impl_->UpdateOperation(request, &response);
+
+ if (response.error == KM_ERROR_OK) {
+ resultConsumed = response.input_consumed;
+ resultParams = kmParamSet2Hidl(response.output_params);
+ resultBlob = kmBuffer2hidlVec(response.output);
+ }
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultConsumed, resultParams, resultBlob);
+ return Void();
+}
+
+Return<void> TrustyKeymaster4Device::finish(uint64_t operationHandle,
+ const hidl_vec<KeyParameter>& inParams,
+ const hidl_vec<uint8_t>& input,
+ const hidl_vec<uint8_t>& signature,
+ const HardwareAuthToken& authToken,
+ const VerificationToken& verificationToken,
+ finish_cb _hidl_cb) {
+ (void)authToken;
+ (void)verificationToken;
+ FinishOperationRequest request;
+ request.op_handle = operationHandle;
+ request.input.Reinitialize(input.data(), input.size());
+ request.signature.Reinitialize(signature.data(), signature.size());
+ request.additional_params.Reinitialize(KmParamSet(inParams));
+
+ FinishOperationResponse response;
+ impl_->FinishOperation(request, &response);
+
+ hidl_vec<KeyParameter> resultParams;
+ hidl_vec<uint8_t> resultBlob;
+ if (response.error == KM_ERROR_OK) {
+ resultParams = kmParamSet2Hidl(response.output_params);
+ resultBlob = kmBuffer2hidlVec(response.output);
+ }
+ _hidl_cb(legacy_enum_conversion(response.error), resultParams, resultBlob);
+ return Void();
+}
+
+Return<ErrorCode> TrustyKeymaster4Device::abort(uint64_t operationHandle) {
+ AbortOperationRequest request;
+ request.op_handle = operationHandle;
+
+ AbortOperationResponse response;
+ impl_->AbortOperation(request, &response);
+
+ return legacy_enum_conversion(response.error);
+}
+} // namespace V4_0
+} // namespace keymaster
diff --git a/trusty/keymaster/4.0/android.hardware.keymaster@4.0-service.trusty.rc b/trusty/keymaster/4.0/android.hardware.keymaster@4.0-service.trusty.rc
new file mode 100644
index 0000000..72c9167
--- /dev/null
+++ b/trusty/keymaster/4.0/android.hardware.keymaster@4.0-service.trusty.rc
@@ -0,0 +1,4 @@
+service vendor.keymaster-4-0 /vendor/bin/hw/android.hardware.keymaster@4.0-service.trusty
+ class early_hal
+ user nobody
+ group drmrpc
diff --git a/trusty/keymaster/4.0/service.cpp b/trusty/keymaster/4.0/service.cpp
new file mode 100644
index 0000000..96eb584
--- /dev/null
+++ b/trusty/keymaster/4.0/service.cpp
@@ -0,0 +1,43 @@
+/*
+**
+** Copyright 2018, 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/logging.h>
+#include <android/hardware/keymaster/4.0/IKeymasterDevice.h>
+#include <hidl/HidlTransportSupport.h>
+#include <trusty_keymaster/TrustyKeymaster.h>
+#include <trusty_keymaster/TrustyKeymaster4Device.h>
+
+int main() {
+ ::android::hardware::configureRpcThreadpool(1, true);
+ auto trustyKeymaster = new keymaster::TrustyKeymaster();
+ int err = trustyKeymaster->Initialize();
+ if (err != 0) {
+ LOG(FATAL) << "Could not initialize TrustyKeymaster (" << err << ")";
+ return -1;
+ }
+
+ auto keymaster = new ::keymaster::V4_0::TrustyKeymaster4Device(trustyKeymaster);
+
+ auto status = keymaster->registerAsService();
+ if (status != android::OK) {
+ LOG(FATAL) << "Could not register service for Keymaster 4.0 (" << status << ")";
+ return -1;
+ }
+
+ android::hardware::joinRpcThreadpool();
+ return -1; // Should never get here.
+}
diff --git a/trusty/keymaster/Android.bp b/trusty/keymaster/Android.bp
index 819851f..d107b78 100644
--- a/trusty/keymaster/Android.bp
+++ b/trusty/keymaster/Android.bp
@@ -108,3 +108,34 @@
"android.hardware.keymaster@3.0"
],
}
+
+cc_binary {
+ name: "android.hardware.keymaster@4.0-service.trusty",
+ defaults: ["hidl_defaults"],
+ relative_install_path: "hw",
+ vendor: true,
+ init_rc: ["4.0/android.hardware.keymaster@4.0-service.trusty.rc"],
+ srcs: [
+ "4.0/service.cpp",
+ "4.0/TrustyKeymaster4Device.cpp",
+ "ipc/trusty_keymaster_ipc.cpp",
+ "TrustyKeymaster.cpp",
+ ],
+
+ local_include_dirs: ["include"],
+
+ shared_libs: [
+ "liblog",
+ "libcutils",
+ "libdl",
+ "libbase",
+ "libutils",
+ "libhardware",
+ "libhidlbase",
+ "libhidltransport",
+ "libtrusty",
+ "libkeymaster_messages",
+ "libkeymaster4",
+ "android.hardware.keymaster@4.0"
+ ],
+}
diff --git a/trusty/keymaster/TrustyKeymaster.cpp b/trusty/keymaster/TrustyKeymaster.cpp
index 7f5e87f..f3ef747 100644
--- a/trusty/keymaster/TrustyKeymaster.cpp
+++ b/trusty/keymaster/TrustyKeymaster.cpp
@@ -172,24 +172,25 @@
ForwardCommand(KM_ABORT_OPERATION, request, response);
}
-/* Methods for Keymaster 4.0 functionality -- not yet implemented */
GetHmacSharingParametersResponse TrustyKeymaster::GetHmacSharingParameters() {
+ // Dummy empty buffer to allow ForwardCommand to have something to serialize
+ Buffer request;
GetHmacSharingParametersResponse response;
- response.error = KM_ERROR_UNIMPLEMENTED;
+ ForwardCommand(KM_GET_HMAC_SHARING_PARAMETERS, request, &response);
return response;
}
ComputeSharedHmacResponse TrustyKeymaster::ComputeSharedHmac(
- const ComputeSharedHmacRequest& /* request */) {
+ const ComputeSharedHmacRequest& request) {
ComputeSharedHmacResponse response;
- response.error = KM_ERROR_UNIMPLEMENTED;
+ ForwardCommand(KM_COMPUTE_SHARED_HMAC, request, &response);
return response;
}
VerifyAuthorizationResponse TrustyKeymaster::VerifyAuthorization(
- const VerifyAuthorizationRequest& /* request */) {
+ const VerifyAuthorizationRequest& request) {
VerifyAuthorizationResponse response;
- response.error = KM_ERROR_UNIMPLEMENTED;
+ ForwardCommand(KM_VERIFY_AUTHORIZATION, request, &response);
return response;
}
diff --git a/trusty/keymaster/include/trusty_keymaster/TrustyKeymaster4Device.h b/trusty/keymaster/include/trusty_keymaster/TrustyKeymaster4Device.h
new file mode 100644
index 0000000..2be15bc
--- /dev/null
+++ b/trusty/keymaster/include/trusty_keymaster/TrustyKeymaster4Device.h
@@ -0,0 +1,105 @@
+/*
+ **
+ ** Copyright 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.
+ */
+
+#ifndef keymaster_V4_0_TrustyKeymaster4Device_H_
+#define keymaster_V4_0_TrustyKeymaster4Device_H_
+
+#include <android/hardware/keymaster/4.0/IKeymasterDevice.h>
+#include <hidl/Status.h>
+#include <trusty_keymaster/TrustyKeymaster.h>
+
+namespace keymaster {
+
+namespace V4_0 {
+
+using ::android::sp;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::keymaster::V4_0::ErrorCode;
+using ::android::hardware::keymaster::V4_0::HardwareAuthenticatorType;
+using ::android::hardware::keymaster::V4_0::HardwareAuthToken;
+using ::android::hardware::keymaster::V4_0::HmacSharingParameters;
+using ::android::hardware::keymaster::V4_0::IKeymasterDevice;
+using ::android::hardware::keymaster::V4_0::KeyCharacteristics;
+using ::android::hardware::keymaster::V4_0::KeyFormat;
+using ::android::hardware::keymaster::V4_0::KeyParameter;
+using ::android::hardware::keymaster::V4_0::KeyPurpose;
+using ::android::hardware::keymaster::V4_0::SecurityLevel;
+using ::android::hardware::keymaster::V4_0::Tag;
+using ::android::hardware::keymaster::V4_0::VerificationToken;
+
+class TrustyKeymaster4Device : public IKeymasterDevice {
+ public:
+ explicit TrustyKeymaster4Device(TrustyKeymaster* impl);
+ virtual ~TrustyKeymaster4Device();
+
+ Return<void> getHardwareInfo(getHardwareInfo_cb _hidl_cb) override;
+ Return<void> getHmacSharingParameters(getHmacSharingParameters_cb _hidl_cb) override;
+ Return<void> computeSharedHmac(const hidl_vec<HmacSharingParameters>& params,
+ computeSharedHmac_cb) override;
+ Return<void> verifyAuthorization(uint64_t challenge,
+ const hidl_vec<KeyParameter>& parametersToVerify,
+ const HardwareAuthToken& authToken,
+ verifyAuthorization_cb _hidl_cb) override;
+ Return<ErrorCode> addRngEntropy(const hidl_vec<uint8_t>& data) override;
+ Return<void> generateKey(const hidl_vec<KeyParameter>& keyParams,
+ generateKey_cb _hidl_cb) override;
+ Return<void> getKeyCharacteristics(const hidl_vec<uint8_t>& keyBlob,
+ const hidl_vec<uint8_t>& clientId,
+ const hidl_vec<uint8_t>& appData,
+ getKeyCharacteristics_cb _hidl_cb) override;
+ Return<void> importKey(const hidl_vec<KeyParameter>& params, KeyFormat keyFormat,
+ const hidl_vec<uint8_t>& keyData, importKey_cb _hidl_cb) override;
+ Return<void> importWrappedKey(const hidl_vec<uint8_t>& wrappedKeyData,
+ const hidl_vec<uint8_t>& wrappingKeyBlob,
+ const hidl_vec<uint8_t>& maskingKey,
+ const hidl_vec<KeyParameter>& unwrappingParams,
+ uint64_t passwordSid, uint64_t biometricSid,
+ importWrappedKey_cb _hidl_cb) override;
+ Return<void> exportKey(KeyFormat exportFormat, const hidl_vec<uint8_t>& keyBlob,
+ const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
+ exportKey_cb _hidl_cb) override;
+ Return<void> attestKey(const hidl_vec<uint8_t>& keyToAttest,
+ const hidl_vec<KeyParameter>& attestParams,
+ attestKey_cb _hidl_cb) override;
+ Return<void> upgradeKey(const hidl_vec<uint8_t>& keyBlobToUpgrade,
+ const hidl_vec<KeyParameter>& upgradeParams,
+ upgradeKey_cb _hidl_cb) override;
+ Return<ErrorCode> deleteKey(const hidl_vec<uint8_t>& keyBlob) override;
+ Return<ErrorCode> deleteAllKeys() override;
+ Return<ErrorCode> destroyAttestationIds() override;
+ Return<void> begin(KeyPurpose purpose, const hidl_vec<uint8_t>& key,
+ const hidl_vec<KeyParameter>& inParams, const HardwareAuthToken& authToken,
+ begin_cb _hidl_cb) override;
+ Return<void> update(uint64_t operationHandle, const hidl_vec<KeyParameter>& inParams,
+ const hidl_vec<uint8_t>& input, const HardwareAuthToken& authToken,
+ const VerificationToken& verificationToken, update_cb _hidl_cb) override;
+ Return<void> finish(uint64_t operationHandle, const hidl_vec<KeyParameter>& inParams,
+ const hidl_vec<uint8_t>& input, const hidl_vec<uint8_t>& signature,
+ const HardwareAuthToken& authToken,
+ const VerificationToken& verificationToken, finish_cb _hidl_cb) override;
+ Return<ErrorCode> abort(uint64_t operationHandle) override;
+
+ private:
+ std::unique_ptr<::keymaster::TrustyKeymaster> impl_;
+};
+
+} // namespace V4_0
+} // namespace keymaster
+
+#endif // keymaster_V4_0_TrustyKeymaster4Device_H_
diff --git a/trusty/trusty-base.mk b/trusty/trusty-base.mk
index 00e3dbc..445d3ce 100644
--- a/trusty/trusty-base.mk
+++ b/trusty/trusty-base.mk
@@ -23,7 +23,7 @@
# HAL loading of gatekeeper.trusty.
PRODUCT_PACKAGES += \
- android.hardware.keymaster@3.0-service.trusty \
+ android.hardware.keymaster@4.0-service.trusty \
android.hardware.gatekeeper@1.0-service \
android.hardware.gatekeeper@1.0-impl \
gatekeeper.trusty