Merge "Add deps to files used by backwards compatibility checker"
diff --git a/adb/client/adb_install.cpp b/adb/client/adb_install.cpp
index a6e8998..042a2d6 100644
--- a/adb/client/adb_install.cpp
+++ b/adb/client/adb_install.cpp
@@ -201,69 +201,68 @@
#else
error_exit("fastdeploy is disabled");
#endif
- } else {
- struct stat sb;
- if (stat(file, &sb) == -1) {
- fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
- return 1;
- }
+ }
- unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
- if (local_fd < 0) {
- fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
- return 1;
- }
-
-#ifdef __linux__
- posix_fadvise(local_fd.get(), 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
-#endif
-
- const bool use_abb = can_use_feature(kFeatureAbb);
- std::string error;
- std::vector<std::string> cmd_args = {use_abb ? "package" : "exec:cmd package"};
- cmd_args.reserve(argc + 3);
-
- // don't copy the APK name, but, copy the rest of the arguments as-is
- while (argc-- > 1) {
- if (use_abb) {
- cmd_args.push_back(*argv++);
- } else {
- cmd_args.push_back(escape_arg(*argv++));
- }
- }
-
- // add size parameter [required for streaming installs]
- // do last to override any user specified value
- cmd_args.push_back("-S");
- cmd_args.push_back(
- android::base::StringPrintf("%" PRIu64, static_cast<uint64_t>(sb.st_size)));
-
- if (is_apex) {
- cmd_args.push_back("--apex");
- }
-
- unique_fd remote_fd;
- if (use_abb) {
- remote_fd = send_abb_exec_command(cmd_args, &error);
- } else {
- remote_fd.reset(adb_connect(android::base::Join(cmd_args, " "), &error));
- }
- if (remote_fd < 0) {
- fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
- return 1;
- }
-
- copy_to_file(local_fd.get(), remote_fd.get());
-
- char buf[BUFSIZ];
- read_status_line(remote_fd.get(), buf, sizeof(buf));
- if (!strncmp("Success", buf, 7)) {
- fputs(buf, stdout);
- return 0;
- }
- fprintf(stderr, "adb: failed to install %s: %s", file, buf);
+ struct stat sb;
+ if (stat(file, &sb) == -1) {
+ fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
return 1;
}
+
+ unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
+ if (local_fd < 0) {
+ fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
+ return 1;
+ }
+
+#ifdef __linux__
+ posix_fadvise(local_fd.get(), 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
+#endif
+
+ const bool use_abb = can_use_feature(kFeatureAbbExec);
+ std::string error;
+ std::vector<std::string> cmd_args = {use_abb ? "package" : "exec:cmd package"};
+ cmd_args.reserve(argc + 3);
+
+ // don't copy the APK name, but, copy the rest of the arguments as-is
+ while (argc-- > 1) {
+ if (use_abb) {
+ cmd_args.push_back(*argv++);
+ } else {
+ cmd_args.push_back(escape_arg(*argv++));
+ }
+ }
+
+ // add size parameter [required for streaming installs]
+ // do last to override any user specified value
+ cmd_args.push_back("-S");
+ cmd_args.push_back(android::base::StringPrintf("%" PRIu64, static_cast<uint64_t>(sb.st_size)));
+
+ if (is_apex) {
+ cmd_args.push_back("--apex");
+ }
+
+ unique_fd remote_fd;
+ if (use_abb) {
+ remote_fd = send_abb_exec_command(cmd_args, &error);
+ } else {
+ remote_fd.reset(adb_connect(android::base::Join(cmd_args, " "), &error));
+ }
+ if (remote_fd < 0) {
+ fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
+ return 1;
+ }
+
+ copy_to_file(local_fd.get(), remote_fd.get());
+
+ char buf[BUFSIZ];
+ read_status_line(remote_fd.get(), buf, sizeof(buf));
+ if (!strncmp("Success", buf, 7)) {
+ fputs(buf, stdout);
+ return 0;
+ }
+ fprintf(stderr, "adb: failed to install %s: %s", file, buf);
+ return 1;
}
static int install_app_legacy(int argc, const char** argv, bool use_fastdeploy,
diff --git a/adb/client/commandline.cpp b/adb/client/commandline.cpp
index fe2bdfe..a0818d3 100644
--- a/adb/client/commandline.cpp
+++ b/adb/client/commandline.cpp
@@ -1713,8 +1713,12 @@
}
if (CanUseFeature(features, kFeatureRemountShell)) {
- const char* arg[2] = {"shell", "remount"};
- return adb_shell(2, arg);
+ std::vector<const char*> args = {"shell"};
+ args.insert(args.cend(), argv, argv + argc);
+ return adb_shell(args.size(), args.data());
+ } else if (argc > 1) {
+ auto command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
+ return adb_connect_command(command);
} else {
return adb_connect_command("remount:");
}
diff --git a/adb/transport.h b/adb/transport.h
index 61a3d9a..c38cb1d 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -65,8 +65,10 @@
extern const char* const kFeatureApex;
// adbd has b/110953234 fixed.
extern const char* const kFeatureFixedPushMkdir;
-// adbd supports android binder bridge (abb).
+// adbd supports android binder bridge (abb) in interactive mode using shell protocol.
extern const char* const kFeatureAbb;
+// adbd supports abb using raw pipe.
+extern const char* const kFeatureAbbExec;
// adbd properly updates symlink timestamps on push.
extern const char* const kFeatureFixedPushSymlinkTimestamp;
extern const char* const kFeatureRemountShell;
diff --git a/base/include/android-base/endian.h b/base/include/android-base/endian.h
index 2d0f614..8fa6365 100644
--- a/base/include/android-base/endian.h
+++ b/base/include/android-base/endian.h
@@ -51,8 +51,10 @@
/* macOS has some of the basics. */
#include <sys/_endian.h>
#else
-/* Windows has even less. */
+/* Windows has some of the basics as well. */
#include <sys/param.h>
+#include <winsock2.h>
+/* winsock2.h *must* be included before the following four macros. */
#define htons(x) __builtin_bswap16(x)
#define htonl(x) __builtin_bswap32(x)
#define ntohs(x) __builtin_bswap16(x)
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index fbc8b97..c617c6c 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -176,7 +176,7 @@
if (crasher_pid != -1) {
kill(crasher_pid, SIGKILL);
int status;
- waitpid(crasher_pid, &status, WUNTRACED);
+ TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
}
android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
@@ -196,7 +196,8 @@
InterceptResponse response;
// Timeout for tombstoned intercept is 10 seconds.
- ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
+ ssize_t rc =
+ TIMEOUT(20, TEMP_FAILURE_RETRY(read(intercept_fd.get(), &response, sizeof(response))));
if (rc == -1) {
FAIL() << "failed to read response from tombstoned: " << strerror(errno);
} else if (rc == 0) {
@@ -233,7 +234,7 @@
FAIL() << "crasher pipe uninitialized";
}
- ssize_t rc = write(crasher_pipe.get(), "\n", 1);
+ ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
if (rc == -1) {
FAIL() << "failed to write to crasher pipe: " << strerror(errno);
} else if (rc == 0) {
@@ -243,7 +244,7 @@
void CrasherTest::AssertDeath(int signo) {
int status;
- pid_t pid = TIMEOUT(10, waitpid(crasher_pid, &status, 0));
+ pid_t pid = TIMEOUT(10, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
if (pid != crasher_pid) {
printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
strerror(errno));
@@ -441,7 +442,7 @@
FinishCrasher();
int status;
- ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
+ ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
ASSERT_TRUE(WIFSTOPPED(status));
ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
@@ -603,13 +604,15 @@
policy += "\nclone: 1";
policy += "\nsigaltstack: 1";
policy += "\nnanosleep: 1";
+ policy += "\ngetrlimit: 1";
+ policy += "\nugetrlimit: 1";
FILE* tmp_file = tmpfile();
if (!tmp_file) {
PLOG(FATAL) << "tmpfile failed";
}
- unique_fd tmp_fd(dup(fileno(tmp_file)));
+ unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
PLOG(FATAL) << "failed to write policy to tmpfile";
}
@@ -822,7 +825,7 @@
FinishCrasher();
int status;
- ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
+ ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
ASSERT_TRUE(WIFSTOPPED(status));
ASSERT_EQ(SIGABRT, WSTOPSIG(status));
@@ -837,7 +840,7 @@
regex += R"( \(.+debuggerd_test)";
ASSERT_MATCH(result, regex.c_str());
- ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
+ ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
ASSERT_TRUE(WIFSTOPPED(status));
ASSERT_EQ(SIGABRT, WSTOPSIG(status));
@@ -851,7 +854,7 @@
StartProcess([]() {
android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
- unique_fd fd(open("/dev/null", O_RDONLY | O_CLOEXEC));
+ unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
abort();
}
@@ -886,13 +889,13 @@
raise(DEBUGGER_SIGNAL);
errno = 0;
- rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
+ rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
if (rc != -1 || errno != ECHILD) {
errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
}
_exit(0);
} else {
- rc = waitpid(forkpid, &status, 0);
+ rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
ASSERT_EQ(forkpid, rc);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(0, WEXITSTATUS(status));
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 4737ae4..a7fc628 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -874,7 +874,7 @@
return false;
}
- if (sparse_file* s = sparse_file_import_auto(fd, false, false)) {
+ if (sparse_file* s = sparse_file_import(fd, false, false)) {
buf->image_size = sparse_file_len(s, false, false);
sparse_file_destroy(s);
} else {
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index f73b189..bb941dd 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -32,6 +32,7 @@
"libfs_mgr",
"libfstab",
"liblp",
+ "update_metadata-protos",
],
whole_static_libs: [
"libext2_uuid",
@@ -41,6 +42,9 @@
header_libs: [
"libfiemap_headers",
],
+ export_static_lib_headers: [
+ "update_metadata-protos",
+ ],
export_header_lib_headers: [
"libfiemap_headers",
],
@@ -51,6 +55,7 @@
name: "libsnapshot_sources",
srcs: [
"snapshot.cpp",
+ "snapshot_metadata_updater.cpp",
"partition_cow_creator.cpp",
"utility.cpp",
],
@@ -87,10 +92,12 @@
srcs: [
"snapshot_test.cpp",
"partition_cow_creator_test.cpp",
+ "snapshot_metadata_updater_test.cpp",
"test_helpers.cpp",
],
shared_libs: [
"libbinder",
+ "libprotobuf-cpp-lite",
"libutils",
],
static_libs: [
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 6bc09a1..aeeb4aa 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -29,6 +29,7 @@
#include <libfiemap/image_manager.h>
#include <liblp/builder.h>
#include <liblp/liblp.h>
+#include <update_engine/update_metadata.pb.h>
#ifndef FRIEND_TEST
#define FRIEND_TEST(test_set_name, individual_test) \
@@ -89,6 +90,7 @@
using IPartitionOpener = android::fs_mgr::IPartitionOpener;
using LpMetadata = android::fs_mgr::LpMetadata;
using MetadataBuilder = android::fs_mgr::MetadataBuilder;
+ using DeltaArchiveManifest = chromeos_update_engine::DeltaArchiveManifest;
public:
// Dependency injection for testing.
@@ -98,6 +100,7 @@
virtual std::string GetGsidDir() const = 0;
virtual std::string GetMetadataDir() const = 0;
virtual std::string GetSlotSuffix() const = 0;
+ virtual std::string GetOtherSlotSuffix() const = 0;
virtual std::string GetSuperDevice(uint32_t slot) const = 0;
virtual const IPartitionOpener& GetPartitionOpener() const = 0;
virtual bool IsOverlayfsSetup() const = 0;
@@ -169,9 +172,7 @@
// Create necessary COW device / files for OTA clients. New logical partitions will be added to
// group "cow" in target_metadata. Regions of partitions of current_metadata will be
// "write-protected" and snapshotted.
- bool CreateUpdateSnapshots(MetadataBuilder* target_metadata, const std::string& target_suffix,
- MetadataBuilder* current_metadata, const std::string& current_suffix,
- const std::map<std::string, uint64_t>& cow_sizes);
+ bool CreateUpdateSnapshots(const DeltaArchiveManifest& manifest);
// Map a snapshotted partition for OTA clients to write to. Write-protected regions are
// determined previously in CreateSnapshots.
diff --git a/fs_mgr/libsnapshot/partition_cow_creator.cpp b/fs_mgr/libsnapshot/partition_cow_creator.cpp
index 3163e61..4250d23 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator.cpp
+++ b/fs_mgr/libsnapshot/partition_cow_creator.cpp
@@ -25,6 +25,9 @@
using android::fs_mgr::Interval;
using android::fs_mgr::kDefaultBlockSize;
using android::fs_mgr::Partition;
+using chromeos_update_engine::InstallOperation;
+template <typename T>
+using RepeatedPtrField = google::protobuf::RepeatedPtrField<T>;
namespace android {
namespace snapshot {
@@ -117,9 +120,15 @@
return snapshot_size;
}
-std::optional<PartitionCowCreator::Return> PartitionCowCreator::Run() {
+std::optional<uint64_t> PartitionCowCreator::GetCowSize(uint64_t snapshot_size) {
+ // TODO: Use |operations|. to determine a minimum COW size.
+ // kCowEstimateFactor is good for prototyping but we can't use that in production.
static constexpr double kCowEstimateFactor = 1.05;
+ auto cow_size = RoundUp(snapshot_size * kCowEstimateFactor, kDefaultBlockSize);
+ return cow_size;
+}
+std::optional<PartitionCowCreator::Return> PartitionCowCreator::Run() {
CHECK(current_metadata->GetBlockDevicePartitionName(0) == LP_METADATA_DEFAULT_PARTITION_NAME &&
target_metadata->GetBlockDevicePartitionName(0) == LP_METADATA_DEFAULT_PARTITION_NAME);
@@ -135,13 +144,8 @@
ret.snapshot_status.snapshot_size = *snapshot_size;
- // TODO: always read from cow_size when the COW size is written in
- // update package. kCowEstimateFactor is good for prototyping but
- // we can't use that in production.
- if (!cow_size.has_value()) {
- cow_size =
- RoundUp(ret.snapshot_status.snapshot_size * kCowEstimateFactor, kDefaultBlockSize);
- }
+ auto cow_size = GetCowSize(*snapshot_size);
+ if (!cow_size.has_value()) return std::nullopt;
// Compute regions that are free in both current and target metadata. These are the regions
// we can use for COW partition.
diff --git a/fs_mgr/libsnapshot/partition_cow_creator.h b/fs_mgr/libsnapshot/partition_cow_creator.h
index a235914..7c81418 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator.h
+++ b/fs_mgr/libsnapshot/partition_cow_creator.h
@@ -32,20 +32,23 @@
using Interval = android::fs_mgr::Interval;
using MetadataBuilder = android::fs_mgr::MetadataBuilder;
using Partition = android::fs_mgr::Partition;
+ using InstallOperation = chromeos_update_engine::InstallOperation;
+ template <typename T>
+ using RepeatedPtrField = google::protobuf::RepeatedPtrField<T>;
// The metadata that will be written to target metadata slot.
- MetadataBuilder* target_metadata;
+ MetadataBuilder* target_metadata = nullptr;
// The suffix of the target slot.
std::string target_suffix;
// The partition in target_metadata that needs to be snapshotted.
- Partition* target_partition;
+ Partition* target_partition = nullptr;
// The metadata at the current slot (that would be used if the device boots
// normally). This is used to determine which extents are being used.
- MetadataBuilder* current_metadata;
+ MetadataBuilder* current_metadata = nullptr;
// The suffix of the current slot.
std::string current_suffix;
- // The COW size given by client code.
- std::optional<uint64_t> cow_size;
+ // List of operations to be applied on the partition.
+ const RepeatedPtrField<InstallOperation>* operations = nullptr;
struct Return {
SnapshotManager::SnapshotStatus snapshot_status;
@@ -57,6 +60,7 @@
private:
bool HasExtent(Partition* p, Extent* e);
std::optional<uint64_t> GetSnapshotSize();
+ std::optional<uint64_t> GetCowSize(uint64_t snapshot_size);
};
} // namespace snapshot
diff --git a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
index e308943..29d15af 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
+++ b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
@@ -76,14 +76,11 @@
.target_suffix = "_b",
.target_partition = system_b,
.current_metadata = builder_a.get(),
- .current_suffix = "_a",
- .cow_size = 20 * 1024};
+ .current_suffix = "_a"};
auto ret = creator.Run();
ASSERT_TRUE(ret.has_value());
ASSERT_EQ(40 * 1024, ret->snapshot_status.device_size);
ASSERT_EQ(40 * 1024, ret->snapshot_status.snapshot_size);
- ASSERT_EQ(20 * 1024,
- ret->snapshot_status.cow_file_size + ret->snapshot_status.cow_partition_size);
}
} // namespace snapshot
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 15d52f1..b5b3af3 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -39,6 +39,7 @@
#include <liblp/liblp.h>
#include "partition_cow_creator.h"
+#include "snapshot_metadata_updater.h"
#include "utility.h"
namespace android {
@@ -61,6 +62,10 @@
using android::fs_mgr::LpMetadata;
using android::fs_mgr::MetadataBuilder;
using android::fs_mgr::SlotNumberForSlotSuffix;
+using chromeos_update_engine::DeltaArchiveManifest;
+using chromeos_update_engine::InstallOperation;
+template <typename T>
+using RepeatedPtrField = google::protobuf::RepeatedPtrField<T>;
using std::chrono::duration_cast;
using namespace std::chrono_literals;
using namespace std::string_literals;
@@ -74,6 +79,7 @@
std::string GetGsidDir() const override { return "ota"s; }
std::string GetMetadataDir() const override { return "/metadata/ota"s; }
std::string GetSlotSuffix() const override { return fs_mgr_get_slot_suffix(); }
+ std::string GetOtherSlotSuffix() const override { return fs_mgr_get_other_slot_suffix(); }
const android::fs_mgr::IPartitionOpener& GetPartitionOpener() const { return opener_; }
std::string GetSuperDevice(uint32_t slot) const override {
return fs_mgr_get_super_partition_name(slot);
@@ -1713,26 +1719,44 @@
return true;
}
-bool SnapshotManager::CreateUpdateSnapshots(MetadataBuilder* target_metadata,
- const std::string& target_suffix,
- MetadataBuilder* current_metadata,
- const std::string& current_suffix,
- const std::map<std::string, uint64_t>& cow_sizes) {
+bool SnapshotManager::CreateUpdateSnapshots(const DeltaArchiveManifest& manifest) {
auto lock = LockExclusive();
if (!lock) return false;
- // Add _{target_suffix} to COW size map.
- std::map<std::string, uint64_t> suffixed_cow_sizes;
- for (const auto& [name, size] : cow_sizes) {
- suffixed_cow_sizes[name + target_suffix] = size;
+ const auto& opener = device_->GetPartitionOpener();
+ auto current_suffix = device_->GetSlotSuffix();
+ uint32_t current_slot = SlotNumberForSlotSuffix(current_suffix);
+ auto target_suffix = device_->GetOtherSlotSuffix();
+ uint32_t target_slot = SlotNumberForSlotSuffix(target_suffix);
+ auto current_super = device_->GetSuperDevice(current_slot);
+
+ auto current_metadata = MetadataBuilder::New(opener, current_super, current_slot);
+ auto target_metadata =
+ MetadataBuilder::NewForUpdate(opener, current_super, current_slot, target_slot);
+
+ SnapshotMetadataUpdater metadata_updater(target_metadata.get(), target_slot, manifest);
+ if (!metadata_updater.Update()) {
+ LOG(ERROR) << "Cannot calculate new metadata.";
+ return false;
}
- target_metadata->RemoveGroupAndPartitions(kCowGroupName);
if (!target_metadata->AddGroup(kCowGroupName, 0)) {
LOG(ERROR) << "Cannot add group " << kCowGroupName;
return false;
}
+ std::map<std::string, const RepeatedPtrField<InstallOperation>*> install_operation_map;
+ for (const auto& partition_update : manifest.partitions()) {
+ auto suffixed_name = partition_update.partition_name() + target_suffix;
+ auto&& [it, inserted] = install_operation_map.emplace(std::move(suffixed_name),
+ &partition_update.operations());
+ if (!inserted) {
+ LOG(ERROR) << "Duplicated partition " << partition_update.partition_name()
+ << " in update manifest.";
+ return false;
+ }
+ }
+
// TODO(b/134949511): remove this check. Right now, with overlayfs mounted, the scratch
// partition takes up a big chunk of space in super, causing COW images to be created on
// retrofit Virtual A/B devices.
@@ -1757,18 +1781,16 @@
// these devices.
AutoDeviceList created_devices;
- for (auto* target_partition : ListPartitionsWithSuffix(target_metadata, target_suffix)) {
- std::optional<uint64_t> cow_size = std::nullopt;
- auto it = suffixed_cow_sizes.find(target_partition->name());
- if (it != suffixed_cow_sizes.end()) {
- cow_size = it->second;
- LOG(INFO) << "Using provided COW size " << *cow_size << " for partition "
- << target_partition->name();
+ for (auto* target_partition : ListPartitionsWithSuffix(target_metadata.get(), target_suffix)) {
+ const RepeatedPtrField<InstallOperation>* operations = nullptr;
+ auto operations_it = install_operation_map.find(target_partition->name());
+ if (operations_it != install_operation_map.end()) {
+ operations = operations_it->second;
}
// Compute the device sizes for the partition.
- PartitionCowCreator cow_creator{target_metadata, target_suffix, target_partition,
- current_metadata, current_suffix, cow_size};
+ PartitionCowCreator cow_creator{target_metadata.get(), target_suffix, target_partition,
+ current_metadata.get(), current_suffix, operations};
auto cow_creator_ret = cow_creator.Run();
if (!cow_creator_ret.has_value()) {
return false;
@@ -1846,13 +1868,17 @@
auto& dm = DeviceMapper::Instance();
auto exported_target_metadata = target_metadata->Export();
+ if (exported_target_metadata == nullptr) {
+ LOG(ERROR) << "Cannot export target metadata";
+ return false;
+ }
CreateLogicalPartitionParams cow_params{
.block_device = LP_METADATA_DEFAULT_PARTITION_NAME,
.metadata = exported_target_metadata.get(),
.timeout_ms = std::chrono::milliseconds::max(),
.partition_opener = &device_->GetPartitionOpener(),
};
- for (auto* target_partition : ListPartitionsWithSuffix(target_metadata, target_suffix)) {
+ for (auto* target_partition : ListPartitionsWithSuffix(target_metadata.get(), target_suffix)) {
AutoDeviceList created_devices_for_cow;
if (!UnmapPartitionWithSnapshot(lock.get(), target_partition->name())) {
@@ -1884,6 +1910,12 @@
// Let destructor of created_devices_for_cow to unmap the COW devices.
};
+ if (!UpdatePartitionTable(opener, device_->GetSuperDevice(target_slot),
+ *exported_target_metadata, target_slot)) {
+ LOG(ERROR) << "Cannot write target metadata";
+ return false;
+ }
+
created_devices.Release();
LOG(INFO) << "Successfully created all snapshots for target slot " << target_suffix;
diff --git a/fs_mgr/libsnapshot/snapshot_metadata_updater.cpp b/fs_mgr/libsnapshot/snapshot_metadata_updater.cpp
new file mode 100644
index 0000000..60bf796
--- /dev/null
+++ b/fs_mgr/libsnapshot/snapshot_metadata_updater.cpp
@@ -0,0 +1,273 @@
+//
+// 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 "snapshot_metadata_updater.h"
+
+#include <algorithm>
+#include <map>
+#include <optional>
+#include <set>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <fs_mgr.h>
+#include <libsnapshot/snapshot.h>
+
+using android::fs_mgr::MetadataBuilder;
+using android::fs_mgr::Partition;
+using android::fs_mgr::SlotSuffixForSlotNumber;
+using chromeos_update_engine::DeltaArchiveManifest;
+
+namespace android {
+namespace snapshot {
+SnapshotMetadataUpdater::SnapshotMetadataUpdater(MetadataBuilder* builder, uint32_t target_slot,
+ const DeltaArchiveManifest& manifest)
+ : builder_(builder), target_suffix_(SlotSuffixForSlotNumber(target_slot)) {
+ if (!manifest.has_dynamic_partition_metadata()) {
+ return;
+ }
+
+ // Key: partition name ("system"). Value: group name ("group").
+ // No suffix.
+ std::map<std::string_view, std::string_view> partition_group_map;
+ const auto& metadata_groups = manifest.dynamic_partition_metadata().groups();
+ groups_.reserve(metadata_groups.size());
+ for (const auto& group : metadata_groups) {
+ groups_.emplace_back(Group{group.name() + target_suffix_, &group});
+ for (const auto& partition_name : group.partition_names()) {
+ partition_group_map[partition_name] = group.name();
+ }
+ }
+
+ for (const auto& p : manifest.partitions()) {
+ auto it = partition_group_map.find(p.partition_name());
+ if (it != partition_group_map.end()) {
+ partitions_.emplace_back(Partition{p.partition_name() + target_suffix_,
+ std::string(it->second) + target_suffix_, &p});
+ }
+ }
+}
+
+bool SnapshotMetadataUpdater::ShrinkPartitions() const {
+ for (const auto& partition_update : partitions_) {
+ auto* existing_partition = builder_->FindPartition(partition_update.name);
+ if (existing_partition == nullptr) {
+ continue;
+ }
+ auto new_size = partition_update->new_partition_info().size();
+ if (existing_partition->size() <= new_size) {
+ continue;
+ }
+ if (!builder_->ResizePartition(existing_partition, new_size)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::DeletePartitions() const {
+ std::vector<std::string> partitions_to_delete;
+ // Don't delete partitions in groups where the group name doesn't have target_suffix,
+ // e.g. default.
+ for (auto* existing_partition : ListPartitionsWithSuffix(builder_, target_suffix_)) {
+ auto iter = std::find_if(partitions_.begin(), partitions_.end(),
+ [existing_partition](auto&& partition_update) {
+ return partition_update.name == existing_partition->name();
+ });
+ // Update package metadata doesn't have this partition. Prepare to delete it.
+ // Not deleting from builder_ yet because it may break ListPartitionsWithSuffix if it were
+ // to return an iterable view of builder_.
+ if (iter == partitions_.end()) {
+ partitions_to_delete.push_back(existing_partition->name());
+ }
+ }
+
+ for (const auto& partition_name : partitions_to_delete) {
+ builder_->RemovePartition(partition_name);
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::MovePartitionsToDefault() const {
+ for (const auto& partition_update : partitions_) {
+ auto* existing_partition = builder_->FindPartition(partition_update.name);
+ if (existing_partition == nullptr) {
+ continue;
+ }
+ if (existing_partition->group_name() == partition_update.group_name) {
+ continue;
+ }
+ // Move to "default" group (which doesn't have maximum size constraint)
+ // temporarily.
+ if (!builder_->ChangePartitionGroup(existing_partition, android::fs_mgr::kDefaultGroup)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::ShrinkGroups() const {
+ for (const auto& group_update : groups_) {
+ auto* existing_group = builder_->FindGroup(group_update.name);
+ if (existing_group == nullptr) {
+ continue;
+ }
+ if (existing_group->maximum_size() <= group_update->size()) {
+ continue;
+ }
+ if (!builder_->ChangeGroupSize(existing_group->name(), group_update->size())) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::DeleteGroups() const {
+ std::vector<std::string> existing_groups = builder_->ListGroups();
+ for (const auto& existing_group_name : existing_groups) {
+ // Don't delete groups without target suffix, e.g. default.
+ if (!android::base::EndsWith(existing_group_name, target_suffix_)) {
+ continue;
+ }
+
+ auto iter = std::find_if(groups_.begin(), groups_.end(),
+ [&existing_group_name](auto&& group_update) {
+ return group_update.name == existing_group_name;
+ });
+ // Update package metadata has this group as well, so not deleting it.
+ if (iter != groups_.end()) {
+ continue;
+ }
+ // Update package metadata doesn't have this group. Before deleting it, sanity check that it
+ // doesn't have any partitions left. Update metadata shouldn't assign any partitions to this
+ // group, so all partitions that originally belong to this group should be moved by
+ // MovePartitionsToDefault at this point.
+ auto existing_partitions_in_group = builder_->ListPartitionsInGroup(existing_group_name);
+ if (!existing_partitions_in_group.empty()) {
+ std::vector<std::string> partition_names_in_group;
+ std::transform(existing_partitions_in_group.begin(), existing_partitions_in_group.end(),
+ std::back_inserter(partition_names_in_group),
+ [](auto* p) { return p->name(); });
+ LOG(ERROR)
+ << "Group " << existing_group_name
+ << " cannot be deleted because the following partitions are left unassigned: ["
+ << android::base::Join(partition_names_in_group, ",") << "]";
+ return false;
+ }
+ builder_->RemoveGroupAndPartitions(existing_group_name);
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::AddGroups() const {
+ for (const auto& group_update : groups_) {
+ if (builder_->FindGroup(group_update.name) == nullptr) {
+ if (!builder_->AddGroup(group_update.name, group_update->size())) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::GrowGroups() const {
+ for (const auto& group_update : groups_) {
+ auto* existing_group = builder_->FindGroup(group_update.name);
+ if (existing_group == nullptr) {
+ continue;
+ }
+ if (existing_group->maximum_size() >= group_update->size()) {
+ continue;
+ }
+ if (!builder_->ChangeGroupSize(existing_group->name(), group_update->size())) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::AddPartitions() const {
+ for (const auto& partition_update : partitions_) {
+ if (builder_->FindPartition(partition_update.name) == nullptr) {
+ auto* p =
+ builder_->AddPartition(partition_update.name, partition_update.group_name,
+ LP_PARTITION_ATTR_READONLY | LP_PARTITION_ATTR_UPDATED);
+ if (p == nullptr) {
+ return false;
+ }
+ }
+ }
+ // Will be resized in GrowPartitions.
+ return true;
+}
+
+bool SnapshotMetadataUpdater::GrowPartitions() const {
+ for (const auto& partition_update : partitions_) {
+ auto* existing_partition = builder_->FindPartition(partition_update.name);
+ if (existing_partition == nullptr) {
+ continue;
+ }
+ auto new_size = partition_update->new_partition_info().size();
+ if (existing_partition->size() >= new_size) {
+ continue;
+ }
+ if (!builder_->ResizePartition(existing_partition, new_size)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::MovePartitionsToCorrectGroup() const {
+ for (const auto& partition_update : partitions_) {
+ auto* existing_partition = builder_->FindPartition(partition_update.name);
+ if (existing_partition == nullptr) {
+ continue;
+ }
+ if (existing_partition->group_name() == partition_update.group_name) {
+ continue;
+ }
+ if (!builder_->ChangePartitionGroup(existing_partition, partition_update.group_name)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SnapshotMetadataUpdater::Update() const {
+ // Remove extents used by COW devices by removing the COW group completely.
+ builder_->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
+
+ // The order of these operations are important so that we
+ // always have enough space to grow or add new partitions / groups.
+ // clang-format off
+ return ShrinkPartitions() &&
+ DeletePartitions() &&
+ MovePartitionsToDefault() &&
+ ShrinkGroups() &&
+ DeleteGroups() &&
+ AddGroups() &&
+ GrowGroups() &&
+ AddPartitions() &&
+ GrowPartitions() &&
+ MovePartitionsToCorrectGroup();
+ // clang-format on
+}
+} // namespace snapshot
+} // namespace android
diff --git a/fs_mgr/libsnapshot/snapshot_metadata_updater.h b/fs_mgr/libsnapshot/snapshot_metadata_updater.h
new file mode 100644
index 0000000..83c9460
--- /dev/null
+++ b/fs_mgr/libsnapshot/snapshot_metadata_updater.h
@@ -0,0 +1,85 @@
+//
+// 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 <stdint.h>
+
+#include <string>
+#include <vector>
+
+#include <liblp/builder.h>
+#include <update_engine/update_metadata.pb.h>
+
+#include "utility.h"
+
+namespace android {
+namespace snapshot {
+
+// Helper class that modifies a super partition metadata for an update for
+// Virtual A/B devices.
+class SnapshotMetadataUpdater {
+ using DeltaArchiveManifest = chromeos_update_engine::DeltaArchiveManifest;
+ using DynamicPartitionMetadata = chromeos_update_engine::DynamicPartitionMetadata;
+ using DynamicPartitionGroup = chromeos_update_engine::DynamicPartitionGroup;
+ using PartitionUpdate = chromeos_update_engine::PartitionUpdate;
+
+ public:
+ // Caller is responsible for ensuring the lifetime of manifest to be longer
+ // than SnapshotMetadataUpdater.
+ SnapshotMetadataUpdater(android::fs_mgr::MetadataBuilder* builder, uint32_t target_slot,
+ const DeltaArchiveManifest& manifest);
+ bool Update() const;
+
+ private:
+ bool RenameGroupSuffix() const;
+ bool ShrinkPartitions() const;
+ bool DeletePartitions() const;
+ bool MovePartitionsToDefault() const;
+ bool ShrinkGroups() const;
+ bool DeleteGroups() const;
+ bool AddGroups() const;
+ bool GrowGroups() const;
+ bool AddPartitions() const;
+ bool GrowPartitions() const;
+ bool MovePartitionsToCorrectGroup() const;
+
+ // Wraps a DynamicPartitionGroup with a slot-suffixed name. Always use
+ // .name instead of ->name() because .name has the slot suffix (e.g.
+ // .name is "group_b" and ->name() is "group".)
+ struct Group {
+ std::string name;
+ const DynamicPartitionGroup* group;
+ const DynamicPartitionGroup* operator->() const { return group; }
+ };
+ // Wraps a PartitionUpdate with a slot-suffixed name / group name. Always use
+ // .name instead of ->partition_name() because .name has the slot suffix (e.g.
+ // .name is "system_b" and ->partition_name() is "system".)
+ struct Partition {
+ std::string name;
+ std::string group_name;
+ const PartitionUpdate* partition;
+ const PartitionUpdate* operator->() const { return partition; }
+ };
+
+ android::fs_mgr::MetadataBuilder* const builder_;
+ const std::string target_suffix_;
+ std::vector<Group> groups_;
+ std::vector<Partition> partitions_;
+};
+
+} // namespace snapshot
+} // namespace android
diff --git a/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
new file mode 100644
index 0000000..535653a
--- /dev/null
+++ b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
@@ -0,0 +1,328 @@
+//
+// 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 "snapshot_metadata_updater.h"
+
+#include <memory>
+#include <string>
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <liblp/builder.h>
+#include <storage_literals/storage_literals.h>
+
+#include "test_helpers.h"
+
+using namespace android::storage_literals;
+using android::fs_mgr::LpMetadata;
+using android::fs_mgr::MetadataBuilder;
+using android::fs_mgr::SlotSuffixForSlotNumber;
+using chromeos_update_engine::DeltaArchiveManifest;
+using chromeos_update_engine::DynamicPartitionGroup;
+using chromeos_update_engine::PartitionUpdate;
+using testing::AssertionFailure;
+using testing::AssertionResult;
+using testing::AssertionSuccess;
+
+namespace android {
+namespace snapshot {
+
+class SnapshotMetadataUpdaterTest : public ::testing::TestWithParam<uint32_t> {
+ public:
+ void SetUp() override {
+ target_slot_ = GetParam();
+ target_suffix_ = SlotSuffixForSlotNumber(target_slot_);
+ builder_ = MetadataBuilder::New(4_GiB + 1_MiB, 4_KiB, 2);
+
+ group_ = manifest_.mutable_dynamic_partition_metadata()->add_groups();
+ group_->set_name("group");
+ group_->set_size(4_GiB);
+ group_->add_partition_names("system");
+ group_->add_partition_names("vendor");
+ system_ = manifest_.add_partitions();
+ system_->set_partition_name("system");
+ SetSize(system_, 2_GiB);
+ vendor_ = manifest_.add_partitions();
+ vendor_->set_partition_name("vendor");
+ SetSize(vendor_, 1_GiB);
+
+ ASSERT_TRUE(FillFakeMetadata(builder_.get(), manifest_, target_suffix_));
+ }
+
+ // Append suffix to name.
+ std::string T(std::string_view name) { return std::string(name) + target_suffix_; }
+
+ AssertionResult UpdateAndExport() {
+ SnapshotMetadataUpdater updater(builder_.get(), target_slot_, manifest_);
+ if (!updater.Update()) {
+ return AssertionFailure() << "Update failed.";
+ }
+
+ exported_ = builder_->Export();
+ if (exported_ == nullptr) {
+ return AssertionFailure() << "Export failed.";
+ }
+ return AssertionSuccess();
+ }
+
+ // Check that in |builder_|, partition |name| + |target_suffix_| has the given |size|.
+ AssertionResult CheckSize(std::string_view name, uint64_t size) {
+ auto p = builder_->FindPartition(T(name));
+ if (p == nullptr) {
+ return AssertionFailure() << "Cannot find partition " << T(name);
+ }
+ if (p->size() != size) {
+ return AssertionFailure() << "Partition " << T(name) << " should be " << size
+ << " bytes, but is " << p->size() << " bytes.";
+ }
+ return AssertionSuccess() << "Partition" << T(name) << " is " << size << " bytes.";
+ }
+
+ // Check that in |builder_|, group |name| + |target_suffix_| has the given |size|.
+ AssertionResult CheckGroupSize(std::string_view name, uint64_t size) {
+ auto g = builder_->FindGroup(T(name));
+ if (g == nullptr) {
+ return AssertionFailure() << "Cannot find group " << T(name);
+ }
+ if (g->maximum_size() != size) {
+ return AssertionFailure() << "Group " << T(name) << " should be " << size
+ << " bytes, but is " << g->maximum_size() << " bytes.";
+ }
+ return AssertionSuccess() << "Group" << T(name) << " is " << size << " bytes.";
+ }
+
+ // Check that in |builder_|, partition |partition_name| + |target_suffix_| is in group
+ // |group_name| + |target_suffix_|;
+ AssertionResult CheckGroupName(std::string_view partition_name, std::string_view group_name) {
+ auto p = builder_->FindPartition(T(partition_name));
+ if (p == nullptr) {
+ return AssertionFailure() << "Cannot find partition " << T(partition_name);
+ }
+ if (p->group_name() != T(group_name)) {
+ return AssertionFailure() << "Partition " << T(partition_name) << " should be in "
+ << T(group_name) << ", but is in " << p->group_name() << ".";
+ }
+ return AssertionSuccess() << "Partition" << T(partition_name) << " is in " << T(group_name)
+ << ".";
+ }
+
+ std::unique_ptr<MetadataBuilder> builder_;
+ uint32_t target_slot_;
+ std::string target_suffix_;
+ DeltaArchiveManifest manifest_;
+ std::unique_ptr<LpMetadata> exported_;
+ DynamicPartitionGroup* group_ = nullptr;
+ PartitionUpdate* system_ = nullptr;
+ PartitionUpdate* vendor_ = nullptr;
+};
+
+TEST_P(SnapshotMetadataUpdaterTest, NoChange) {
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckGroupSize("group", 4_GiB));
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_TRUE(CheckGroupName("system", "group"));
+ EXPECT_TRUE(CheckSize("vendor", 1_GiB));
+ EXPECT_TRUE(CheckGroupName("vendor", "group"));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, GrowWithinBounds) {
+ SetSize(system_, 2_GiB + 512_MiB);
+ SetSize(vendor_, 1_GiB + 512_MiB);
+
+ ASSERT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB + 512_MiB));
+ EXPECT_TRUE(CheckSize("vendor", 1_GiB + 512_MiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, GrowOverSuper) {
+ SetSize(system_, 3_GiB);
+ SetSize(vendor_, 1_GiB + 512_MiB);
+
+ EXPECT_FALSE(UpdateAndExport());
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, GrowOverGroup) {
+ SetSize(system_, 3_GiB);
+ SetSize(vendor_, 1_GiB + 4_KiB);
+
+ EXPECT_FALSE(UpdateAndExport());
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, Add) {
+ group_->add_partition_names("product");
+ auto product = manifest_.add_partitions();
+ product->set_partition_name("product");
+ SetSize(product, 1_GiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_TRUE(CheckSize("vendor", 1_GiB));
+ EXPECT_TRUE(CheckSize("product", 1_GiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, AddTooBig) {
+ group_->add_partition_names("product");
+ auto product = manifest_.add_partitions();
+ product->set_partition_name("product");
+ SetSize(product, 1_GiB + 4_KiB);
+
+ EXPECT_FALSE(UpdateAndExport());
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, ShrinkAll) {
+ SetSize(system_, 1_GiB);
+ SetSize(vendor_, 512_MiB);
+
+ ASSERT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 1_GiB));
+ EXPECT_TRUE(CheckSize("vendor", 512_MiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, ShrinkAndGrow) {
+ SetSize(system_, 3_GiB + 512_MiB);
+ SetSize(vendor_, 512_MiB);
+
+ ASSERT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 3_GiB + 512_MiB));
+ EXPECT_TRUE(CheckSize("vendor", 512_MiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, ShrinkAndAdd) {
+ SetSize(system_, 2_GiB);
+ SetSize(vendor_, 512_MiB);
+ group_->add_partition_names("product");
+ auto product = manifest_.add_partitions();
+ product->set_partition_name("product");
+ SetSize(product, 1_GiB + 512_MiB);
+
+ ASSERT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_TRUE(CheckSize("vendor", 512_MiB));
+ EXPECT_TRUE(CheckSize("product", 1_GiB + 512_MiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, Delete) {
+ group_->mutable_partition_names()->RemoveLast();
+ // No need to delete it from manifest.partitions as SnapshotMetadataUpdater
+ // should ignore them (treat them as static partitions).
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_EQ(nullptr, builder_->FindPartition(T("vendor")));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, DeleteAndGrow) {
+ group_->mutable_partition_names()->RemoveLast();
+ SetSize(system_, 4_GiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 4_GiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, DeleteAndAdd) {
+ group_->mutable_partition_names()->RemoveLast();
+ group_->add_partition_names("product");
+ auto product = manifest_.add_partitions();
+ product->set_partition_name("product");
+ SetSize(product, 2_GiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_EQ(nullptr, builder_->FindPartition(T("vendor")));
+ EXPECT_TRUE(CheckSize("product", 2_GiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, GrowGroup) {
+ group_->set_size(4_GiB + 512_KiB);
+ SetSize(system_, 2_GiB + 256_KiB);
+ SetSize(vendor_, 2_GiB + 256_KiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 2_GiB + 256_KiB));
+ EXPECT_TRUE(CheckSize("vendor", 2_GiB + 256_KiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, ShrinkGroup) {
+ group_->set_size(1_GiB);
+ SetSize(system_, 512_MiB);
+ SetSize(vendor_, 512_MiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckSize("system", 512_MiB));
+ EXPECT_TRUE(CheckSize("vendor", 512_MiB));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, MoveToNewGroup) {
+ group_->mutable_partition_names()->RemoveLast();
+ group_->set_size(2_GiB);
+
+ auto another_group = manifest_.mutable_dynamic_partition_metadata()->add_groups();
+ another_group->set_name("another_group");
+ another_group->set_size(2_GiB);
+ another_group->add_partition_names("vendor");
+ SetSize(vendor_, 2_GiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_TRUE(CheckGroupSize("group", 2_GiB));
+ EXPECT_TRUE(CheckGroupSize("another_group", 2_GiB));
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_TRUE(CheckGroupName("system", "group"));
+ EXPECT_TRUE(CheckSize("vendor", 2_GiB));
+ EXPECT_TRUE(CheckGroupName("vendor", "another_group"));
+}
+
+TEST_P(SnapshotMetadataUpdaterTest, DeleteAndAddGroup) {
+ manifest_.mutable_dynamic_partition_metadata()->mutable_groups()->RemoveLast();
+ group_ = nullptr;
+
+ auto another_group = manifest_.mutable_dynamic_partition_metadata()->add_groups();
+ another_group->set_name("another_group");
+ another_group->set_size(4_GiB);
+ another_group->add_partition_names("system");
+ another_group->add_partition_names("vendor");
+ another_group->add_partition_names("product");
+ auto product = manifest_.add_partitions();
+ product->set_partition_name("product");
+ SetSize(product, 1_GiB);
+
+ EXPECT_TRUE(UpdateAndExport());
+
+ EXPECT_EQ(nullptr, builder_->FindGroup(T("group")));
+ EXPECT_TRUE(CheckGroupSize("another_group", 4_GiB));
+ EXPECT_TRUE(CheckSize("system", 2_GiB));
+ EXPECT_TRUE(CheckGroupName("system", "another_group"));
+ EXPECT_TRUE(CheckSize("vendor", 1_GiB));
+ EXPECT_TRUE(CheckGroupName("vendor", "another_group"));
+ EXPECT_TRUE(CheckSize("product", 1_GiB));
+ EXPECT_TRUE(CheckGroupName("product", "another_group"));
+}
+
+INSTANTIATE_TEST_SUITE_P(, SnapshotMetadataUpdaterTest, testing::Values(0, 1));
+
+} // namespace snapshot
+} // namespace android
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index e9835d0..36982a9 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -50,6 +50,8 @@
using android::fs_mgr::GetPartitionGroupName;
using android::fs_mgr::GetPartitionName;
using android::fs_mgr::MetadataBuilder;
+using chromeos_update_engine::DeltaArchiveManifest;
+using chromeos_update_engine::PartitionUpdate;
using namespace ::testing;
using namespace android::fs_mgr::testing;
using namespace android::storage_literals;
@@ -62,7 +64,8 @@
TestDeviceInfo* test_device = nullptr;
std::string fake_super;
-static constexpr uint64_t kSuperSize = 16_MiB;
+static constexpr uint64_t kSuperSize = 16_MiB + 4_KiB;
+static constexpr uint64_t kGroupSize = 16_MiB;
class SnapshotTest : public ::testing::Test {
public:
@@ -636,28 +639,39 @@
ON_CALL(*GetMockedPropertyFetcher(), GetBoolProperty("ro.virtual_ab.enabled", _))
.WillByDefault(Return(true));
- opener = std::make_unique<TestPartitionOpener>(fake_super);
+ opener_ = std::make_unique<TestPartitionOpener>(fake_super);
- // Initialize source partition metadata. sys_b is similar to system_other.
+ // Create a fake update package metadata.
// Not using full name "system", "vendor", "product" because these names collide with the
// mapped partitions on the running device.
- src = MetadataBuilder::New(*opener, "super", 0);
- ASSERT_NE(nullptr, src);
- auto partition = src->AddPartition("sys_a", 0);
+ // Each test modifies manifest_ slightly to indicate changes to the partition layout.
+ auto group = manifest_.mutable_dynamic_partition_metadata()->add_groups();
+ group->set_name("group");
+ group->set_size(kGroupSize);
+ group->add_partition_names("sys");
+ group->add_partition_names("vnd");
+ group->add_partition_names("prd");
+ sys_ = manifest_.add_partitions();
+ sys_->set_partition_name("sys");
+ SetSize(sys_, 3_MiB);
+ vnd_ = manifest_.add_partitions();
+ vnd_->set_partition_name("vnd");
+ SetSize(vnd_, 3_MiB);
+ prd_ = manifest_.add_partitions();
+ prd_->set_partition_name("prd");
+ SetSize(prd_, 3_MiB);
+
+ // Initialize source partition metadata using |manifest_|.
+ src_ = MetadataBuilder::New(*opener_, "super", 0);
+ ASSERT_TRUE(FillFakeMetadata(src_.get(), manifest_, "_a"));
+ ASSERT_NE(nullptr, src_);
+ // Add sys_b which is like system_other.
+ auto partition = src_->AddPartition("sys_b", 0);
ASSERT_NE(nullptr, partition);
- ASSERT_TRUE(src->ResizePartition(partition, 3_MiB));
- partition = src->AddPartition("vnd_a", 0);
- ASSERT_NE(nullptr, partition);
- ASSERT_TRUE(src->ResizePartition(partition, 3_MiB));
- partition = src->AddPartition("prd_a", 0);
- ASSERT_NE(nullptr, partition);
- ASSERT_TRUE(src->ResizePartition(partition, 3_MiB));
- partition = src->AddPartition("sys_b", 0);
- ASSERT_NE(nullptr, partition);
- ASSERT_TRUE(src->ResizePartition(partition, 1_MiB));
- auto metadata = src->Export();
+ ASSERT_TRUE(src_->ResizePartition(partition, 1_MiB));
+ auto metadata = src_->Export();
ASSERT_NE(nullptr, metadata);
- ASSERT_TRUE(UpdatePartitionTable(*opener, "super", *metadata.get(), 0));
+ ASSERT_TRUE(UpdatePartitionTable(*opener_, "super", *metadata.get(), 0));
// Map source partitions. Additionally, map sys_b to simulate system_other after flashing.
std::string path;
@@ -668,7 +682,7 @@
.metadata_slot = 0,
.partition_name = name,
.timeout_ms = 1s,
- .partition_opener = opener.get(),
+ .partition_opener = opener_.get(),
},
&path));
ASSERT_TRUE(WriteRandomData(path));
@@ -692,22 +706,6 @@
EXPECT_TRUE(UnmapAll());
}
- static AssertionResult ResizePartitions(
- MetadataBuilder* builder,
- const std::vector<std::pair<std::string, uint64_t>>& partition_sizes) {
- for (auto&& [name, size] : partition_sizes) {
- auto partition = builder->FindPartition(name);
- if (!partition) {
- return AssertionFailure() << "Cannot find partition in metadata " << name;
- }
- if (!builder->ResizePartition(partition, size)) {
- return AssertionFailure()
- << "Cannot resize partition " << name << " to " << size << " bytes";
- }
- }
- return AssertionSuccess();
- }
-
AssertionResult IsPartitionUnchanged(const std::string& name) {
std::string path;
if (!dm_.GetDmDevicePathByName(name, &path)) {
@@ -748,9 +746,14 @@
return AssertionSuccess();
}
- std::unique_ptr<TestPartitionOpener> opener;
- std::unique_ptr<MetadataBuilder> src;
+ std::unique_ptr<TestPartitionOpener> opener_;
+ DeltaArchiveManifest manifest_;
+ std::unique_ptr<MetadataBuilder> src_;
std::map<std::string, std::string> hashes_;
+
+ PartitionUpdate* sys_ = nullptr;
+ PartitionUpdate* vnd_ = nullptr;
+ PartitionUpdate* prd_ = nullptr;
};
// Test full update flow executed by update_engine. Some partitions uses super empty space,
@@ -767,29 +770,19 @@
ASSERT_TRUE(sm->UnmapUpdateSnapshot(name));
}
- // OTA client adjusts the partition sizes before giving it to CreateUpdateSnapshots.
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- // clang-format off
- ASSERT_TRUE(ResizePartitions(tgt.get(), {
- {"sys_b", 4_MiB}, // grows
- {"vnd_b", 4_MiB}, // grows
- {"prd_b", 4_MiB}, // grows
- }));
- // clang-format on
+ // Grow all partitions.
+ SetSize(sys_, 4_MiB);
+ SetSize(vnd_, 4_MiB);
+ SetSize(prd_, 4_MiB);
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
// Test that partitions prioritize using space in super.
+ auto tgt = MetadataBuilder::New(*opener_, "super", 1);
ASSERT_NE(nullptr, tgt->FindPartition("sys_b-cow"));
ASSERT_NE(nullptr, tgt->FindPartition("vnd_b-cow"));
ASSERT_EQ(nullptr, tgt->FindPartition("prd_b-cow"));
- // The metadata slot 1 is now updated.
- auto metadata = tgt->Export();
- ASSERT_NE(nullptr, metadata);
- ASSERT_TRUE(UpdatePartitionTable(*opener, "super", *metadata.get(), 1));
-
// Write some data to target partitions.
for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
std::string path;
@@ -799,7 +792,7 @@
.metadata_slot = 1,
.partition_name = name,
.timeout_ms = 10s,
- .partition_opener = opener.get(),
+ .partition_opener = opener_.get(),
},
&path))
<< name;
@@ -845,49 +838,31 @@
// Test that if new system partitions uses empty space in super, that region is not snapshotted.
TEST_F(SnapshotUpdateTest, DirectWriteEmptySpace) {
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- // clang-format off
- ASSERT_TRUE(ResizePartitions(tgt.get(), {
- {"sys_b", 4_MiB}, // grows
- // vnd_b and prd_b are unchanged
- }));
- // clang-format on
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
-
+ SetSize(sys_, 4_MiB);
+ // vnd_b and prd_b are unchanged.
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
ASSERT_EQ(3_MiB, GetSnapshotSize("sys_b").value_or(0));
}
// Test that if new system partitions uses space of old vendor partition, that region is
// snapshotted.
TEST_F(SnapshotUpdateTest, SnapshotOldPartitions) {
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- // clang-format off
- ASSERT_TRUE(ResizePartitions(tgt.get(), {
- {"vnd_b", 2_MiB}, // shrinks
- {"sys_b", 4_MiB}, // grows
- // prd_b is unchanged
- }));
- // clang-format on
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
-
+ SetSize(sys_, 4_MiB); // grows
+ SetSize(vnd_, 2_MiB); // shrinks
+ // prd_b is unchanged
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
ASSERT_EQ(4_MiB, GetSnapshotSize("sys_b").value_or(0));
}
// Test that even if there seem to be empty space in target metadata, COW partition won't take
// it because they are used by old partitions.
TEST_F(SnapshotUpdateTest, CowPartitionDoNotTakeOldPartitions) {
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- // clang-format off
- ASSERT_TRUE(ResizePartitions(tgt.get(), {
- {"sys_b", 2_MiB}, // shrinks
- // vnd_b and prd_b are unchanged
- }));
- // clang-format on
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
+ SetSize(sys_, 2_MiB); // shrinks
+ // vnd_b and prd_b are unchanged.
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
+ auto tgt = MetadataBuilder::New(*opener_, "super", 1);
+ ASSERT_NE(nullptr, tgt);
auto metadata = tgt->Export();
ASSERT_NE(nullptr, metadata);
std::vector<std::string> written;
@@ -903,7 +878,7 @@
.metadata = metadata.get(),
.partition = &p,
.timeout_ms = 1s,
- .partition_opener = opener.get(),
+ .partition_opener = opener_.get(),
},
&path));
ASSERT_TRUE(WriteRandomData(path));
@@ -934,14 +909,8 @@
// Redo the update.
ASSERT_TRUE(sm->BeginUpdate());
ASSERT_TRUE(sm->UnmapUpdateSnapshot("sys_b"));
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
- // The metadata slot 1 is now updated.
- auto metadata = tgt->Export();
- ASSERT_NE(nullptr, metadata);
- ASSERT_TRUE(UpdatePartitionTable(*opener, "super", *metadata.get(), 1));
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
// Check that target partitions can be mapped.
for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
@@ -952,7 +921,7 @@
.metadata_slot = 1,
.partition_name = name,
.timeout_ms = 10s,
- .partition_opener = opener.get(),
+ .partition_opener = opener_.get(),
},
&path))
<< name;
@@ -964,14 +933,8 @@
// Execute the update.
ASSERT_TRUE(sm->BeginUpdate());
ASSERT_TRUE(sm->UnmapUpdateSnapshot("sys_b"));
- auto tgt = MetadataBuilder::NewForUpdate(*opener, "super", 0, 1);
- ASSERT_NE(nullptr, tgt);
- ASSERT_TRUE(sm->CreateUpdateSnapshots(tgt.get(), "_b", src.get(), "_a", {}));
- // The metadata slot 1 is now updated.
- auto metadata = tgt->Export();
- ASSERT_NE(nullptr, metadata);
- ASSERT_TRUE(UpdatePartitionTable(*opener, "super", *metadata.get(), 1));
+ ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
// Write some data to target partitions.
for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
@@ -982,7 +945,7 @@
.metadata_slot = 1,
.partition_name = name,
.timeout_ms = 10s,
- .partition_opener = opener.get(),
+ .partition_opener = opener_.get(),
},
&path))
<< name;
diff --git a/fs_mgr/libsnapshot/test_helpers.cpp b/fs_mgr/libsnapshot/test_helpers.cpp
index e12ec77..1a6a593 100644
--- a/fs_mgr/libsnapshot/test_helpers.cpp
+++ b/fs_mgr/libsnapshot/test_helpers.cpp
@@ -27,6 +27,8 @@
using android::base::unique_fd;
using android::base::WriteFully;
using android::fiemap::IImageManager;
+using testing::AssertionFailure;
+using testing::AssertionSuccess;
void DeleteBackingImage(IImageManager* manager, const std::string& name) {
if (manager->IsImageMapped(name)) {
@@ -110,5 +112,40 @@
return ToHexString(out, sizeof(out));
}
+AssertionResult FillFakeMetadata(MetadataBuilder* builder, const DeltaArchiveManifest& manifest,
+ const std::string& suffix) {
+ for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
+ if (!builder->AddGroup(group.name() + suffix, group.size())) {
+ return AssertionFailure()
+ << "Cannot add group " << group.name() << " with size " << group.size();
+ }
+ for (const auto& partition_name : group.partition_names()) {
+ auto p = builder->AddPartition(partition_name + suffix, group.name() + suffix,
+ 0 /* attr */);
+ if (!p) {
+ return AssertionFailure() << "Cannot add partition " << partition_name + suffix
+ << " to group " << group.name() << suffix;
+ }
+ }
+ }
+ for (const auto& partition : manifest.partitions()) {
+ auto p = builder->FindPartition(partition.partition_name() + suffix);
+ if (!p) {
+ return AssertionFailure() << "Cannot resize partition " << partition.partition_name()
+ << suffix << "; it is not found.";
+ }
+ if (!builder->ResizePartition(p, partition.new_partition_info().size())) {
+ return AssertionFailure()
+ << "Cannot resize partition " << partition.partition_name() << suffix
+ << " to size " << partition.new_partition_info().size();
+ }
+ }
+ return AssertionSuccess();
+}
+
+void SetSize(PartitionUpdate* partition_update, uint64_t size) {
+ partition_update->mutable_new_partition_info()->set_size(size);
+}
+
} // namespace snapshot
} // namespace android
diff --git a/fs_mgr/libsnapshot/test_helpers.h b/fs_mgr/libsnapshot/test_helpers.h
index d917e35..0303a14 100644
--- a/fs_mgr/libsnapshot/test_helpers.h
+++ b/fs_mgr/libsnapshot/test_helpers.h
@@ -17,13 +17,20 @@
#include <optional>
#include <string>
+#include <gtest/gtest.h>
#include <libfiemap/image_manager.h>
#include <liblp/partition_opener.h>
#include <libsnapshot/snapshot.h>
+#include <update_engine/update_metadata.pb.h>
namespace android {
namespace snapshot {
+using android::fs_mgr::MetadataBuilder;
+using chromeos_update_engine::DeltaArchiveManifest;
+using chromeos_update_engine::PartitionUpdate;
+using testing::AssertionResult;
+
using namespace std::string_literals;
// Redirect requests for "super" to our fake super partition.
@@ -48,6 +55,7 @@
std::string GetGsidDir() const override { return "ota/test"s; }
std::string GetMetadataDir() const override { return "/metadata/ota/test"s; }
std::string GetSlotSuffix() const override { return slot_suffix_; }
+ std::string GetOtherSlotSuffix() const override { return slot_suffix_ == "_a" ? "_b" : "_a"; }
std::string GetSuperDevice([[maybe_unused]] uint32_t slot) const override { return "super"; }
const android::fs_mgr::IPartitionOpener& GetPartitionOpener() const override {
return *opener_.get();
@@ -72,5 +80,12 @@
std::optional<std::string> GetHash(const std::string& path);
+// Add partitions and groups described by |manifest|.
+AssertionResult FillFakeMetadata(MetadataBuilder* builder, const DeltaArchiveManifest& manifest,
+ const std::string& suffix);
+
+// In the update package metadata, set a partition with the given size.
+void SetSize(PartitionUpdate* partition_update, uint64_t size);
+
} // namespace snapshot
} // namespace android
diff --git a/fs_mgr/libsnapshot/utility.h b/fs_mgr/libsnapshot/utility.h
index a700c46..75c694c 100644
--- a/fs_mgr/libsnapshot/utility.h
+++ b/fs_mgr/libsnapshot/utility.h
@@ -22,6 +22,7 @@
#include <libfiemap/image_manager.h>
#include <liblp/builder.h>
#include <libsnapshot/snapshot.h>
+#include <update_engine/update_metadata.pb.h>
namespace android {
namespace snapshot {
diff --git a/fs_mgr/libvbmeta/Android.bp b/fs_mgr/libvbmeta/Android.bp
new file mode 100644
index 0000000..937e0f3
--- /dev/null
+++ b/fs_mgr/libvbmeta/Android.bp
@@ -0,0 +1,52 @@
+//
+// 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.
+//
+
+libvbmeta_lib_deps = [
+ "libbase",
+ "libcrypto",
+]
+
+cc_library {
+ name: "libvbmeta",
+ host_supported: true,
+ srcs: [
+ "builder.cpp",
+ "reader.cpp",
+ "utility.cpp",
+ "writer.cpp",
+ ],
+ shared_libs: [
+ "liblog",
+ ] + libvbmeta_lib_deps,
+ export_include_dirs: ["include"],
+}
+
+cc_test_host {
+ name: "libvbmeta_test",
+ static_libs: [
+ "libsparse",
+ "libvbmeta",
+ "libz",
+ ] + libvbmeta_lib_deps,
+ srcs: [
+ "builder_test.cpp",
+ "super_vbmeta_test.cpp",
+ ],
+ required: [
+ "avbtool",
+ "vbmake",
+ ],
+}
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/builder.cpp b/fs_mgr/libvbmeta/builder.cpp
new file mode 100644
index 0000000..a901a4f
--- /dev/null
+++ b/fs_mgr/libvbmeta/builder.cpp
@@ -0,0 +1,214 @@
+/*
+ * 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 "builder.h"
+
+#include <android-base/file.h>
+#include <openssl/sha.h>
+
+#include "reader.h"
+#include "utility.h"
+#include "writer.h"
+
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+using android::base::unique_fd;
+
+namespace android {
+namespace fs_mgr {
+
+SuperVBMetaBuilder::SuperVBMetaBuilder() {}
+
+SuperVBMetaBuilder::SuperVBMetaBuilder(const int super_vbmeta_fd,
+ const std::map<std::string, std::string>& images_path)
+ : super_vbmeta_fd_(super_vbmeta_fd), images_path_(images_path) {}
+
+Result<void> SuperVBMetaBuilder::Build() {
+ for (const auto& [vbmeta_name, file_path] : images_path_) {
+ Result<std::string> content = ReadVBMetaImageFromFile(file_path);
+ if (!content) {
+ return content.error();
+ }
+
+ Result<uint8_t> vbmeta_index = AddVBMetaImage(vbmeta_name);
+ if (!vbmeta_index) {
+ return vbmeta_index.error();
+ }
+
+ Result<void> rv_export_vbmeta_image =
+ ExportVBMetaImageToFile(vbmeta_index.value(), content.value());
+ if (!rv_export_vbmeta_image) {
+ return rv_export_vbmeta_image;
+ }
+ }
+ return {};
+}
+
+Result<std::string> SuperVBMetaBuilder::ReadVBMetaImageFromFile(const std::string& file) {
+ unique_fd source_fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
+ if (source_fd < 0) {
+ return ErrnoError() << "Couldn't open vbmeta image file " << file;
+ }
+
+ Result<uint64_t> file_size = GetFileSize(source_fd);
+ if (!file_size) {
+ return file_size.error();
+ }
+
+ if (file_size.value() > VBMETA_IMAGE_MAX_SIZE) {
+ return Error() << "vbmeta image file size " << file_size.value() << " is too large";
+ }
+
+ std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(VBMETA_IMAGE_MAX_SIZE);
+ if (!android::base::ReadFully(source_fd, buffer.get(), file_size.value())) {
+ return ErrnoError() << "Couldn't read vbmeta image file " << file;
+ }
+
+ return std::string(reinterpret_cast<const char*>(buffer.get()), VBMETA_IMAGE_MAX_SIZE);
+}
+
+Result<uint8_t> SuperVBMetaBuilder::GetEmptySlot() {
+ for (uint8_t i = 0; i < VBMETA_IMAGE_MAX_NUM; ++i) {
+ if ((table_.header.in_use & (1 << i)) == 0) return i;
+ }
+ return Error() << "There isn't empty slot in super vbmeta";
+}
+
+Result<uint8_t> SuperVBMetaBuilder::AddVBMetaImage(const std::string& vbmeta_name) {
+ auto desc = std::find_if(
+ table_.descriptors.begin(), table_.descriptors.end(),
+ [&vbmeta_name](const auto& entry) { return entry.vbmeta_name == vbmeta_name; });
+
+ uint8_t slot_number = 0;
+ if (desc != table_.descriptors.end()) {
+ slot_number = desc->vbmeta_index;
+ } else {
+ Result<uint8_t> new_slot = GetEmptySlot();
+ if (!new_slot) {
+ return new_slot;
+ }
+ slot_number = new_slot.value();
+
+ // insert new descriptor into table
+ InternalVBMetaDescriptor new_desc;
+ new_desc.vbmeta_index = slot_number;
+ new_desc.vbmeta_name_length = vbmeta_name.length();
+ new_desc.vbmeta_name = vbmeta_name;
+ memset(new_desc.reserved, 0, sizeof(new_desc.reserved));
+ table_.descriptors.emplace_back(std::move(new_desc));
+
+ // mark slot as in use
+ table_.header.in_use |= (1 << slot_number);
+ }
+
+ return slot_number;
+}
+
+void SuperVBMetaBuilder::DeleteVBMetaImage(const std::string& vbmeta_name) {
+ auto desc = std::find_if(
+ table_.descriptors.begin(), table_.descriptors.end(),
+ [&vbmeta_name](const auto& entry) { return entry.vbmeta_name == vbmeta_name; });
+
+ if (desc != table_.descriptors.end()) {
+ // mark slot as not in use
+ table_.header.in_use &= ~(1 << desc->vbmeta_index);
+
+ // erase descriptor in table
+ table_.descriptors.erase(desc);
+ }
+}
+
+std::unique_ptr<VBMetaTable> SuperVBMetaBuilder::ExportVBMetaTable() {
+ // calculate descriptors size
+ uint32_t descriptors_size = 0;
+ for (const auto& desc : table_.descriptors) {
+ descriptors_size += SUPER_VBMETA_DESCRIPTOR_SIZE + desc.vbmeta_name_length * sizeof(char);
+ }
+
+ // export header
+ table_.header.magic = SUPER_VBMETA_MAGIC;
+ table_.header.major_version = SUPER_VBMETA_MAJOR_VERSION;
+ table_.header.minor_version = SUPER_VBMETA_MINOR_VERSION;
+ table_.header.header_size = SUPER_VBMETA_HEADER_SIZE;
+ table_.header.total_size = SUPER_VBMETA_HEADER_SIZE + descriptors_size;
+ memset(table_.header.checksum, 0, sizeof(table_.header.checksum));
+ table_.header.descriptors_size = descriptors_size;
+ memset(table_.header.reserved, 0, sizeof(table_.header.reserved));
+ std::string serialized_table = SerializeVBMetaTable(table_);
+ ::SHA256(reinterpret_cast<const uint8_t*>(serialized_table.c_str()), table_.header.total_size,
+ &table_.header.checksum[0]);
+
+ return std::make_unique<VBMetaTable>(table_);
+}
+
+Result<void> SuperVBMetaBuilder::ExportVBMetaTableToFile() {
+ std::unique_ptr<VBMetaTable> table = ExportVBMetaTable();
+
+ std::string serialized_table = SerializeVBMetaTable(*table);
+
+ android::base::Result<void> rv_write_primary_vbmeta_table =
+ WritePrimaryVBMetaTable(super_vbmeta_fd_, serialized_table);
+ if (!rv_write_primary_vbmeta_table) {
+ return rv_write_primary_vbmeta_table;
+ }
+
+ android::base::Result<void> rv_write_backup_vbmeta_table =
+ WriteBackupVBMetaTable(super_vbmeta_fd_, serialized_table);
+ return rv_write_backup_vbmeta_table;
+}
+
+Result<void> SuperVBMetaBuilder::ExportVBMetaImageToFile(const uint8_t vbmeta_index,
+ const std::string& vbmeta_image) {
+ Result<void> rv_write_vbmeta_image =
+ WriteVBMetaImage(super_vbmeta_fd_, vbmeta_index, vbmeta_image);
+ if (!rv_write_vbmeta_image) {
+ return rv_write_vbmeta_image;
+ }
+
+ Result<void> rv_validate_vbmeta_image =
+ ValidateVBMetaImage(super_vbmeta_fd_, vbmeta_index, vbmeta_image);
+ return rv_validate_vbmeta_image;
+}
+
+bool WriteToSuperVBMetaFile(const std::string& super_vbmeta_file,
+ const std::map<std::string, std::string>& images_path) {
+ unique_fd super_vbmeta_fd(TEMP_FAILURE_RETRY(
+ open(super_vbmeta_file.c_str(), O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, 0644)));
+ if (super_vbmeta_fd < 0) {
+ PERROR << "Couldn't open super vbmeta file " << super_vbmeta_file;
+ return false;
+ }
+
+ SuperVBMetaBuilder builder(super_vbmeta_fd, images_path);
+
+ Result<void> rv_build = builder.Build();
+ if (!rv_build) {
+ LERROR << rv_build.error();
+ return false;
+ }
+
+ Result<void> rv_export = builder.ExportVBMetaTableToFile();
+ if (!rv_export) {
+ LERROR << rv_export.error();
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/builder.h b/fs_mgr/libvbmeta/builder.h
new file mode 100644
index 0000000..58ea36a
--- /dev/null
+++ b/fs_mgr/libvbmeta/builder.h
@@ -0,0 +1,55 @@
+/*
+ * 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 <map>
+#include <string>
+
+#include <android-base/result.h>
+
+#include "super_vbmeta_format.h"
+
+namespace android {
+namespace fs_mgr {
+
+class SuperVBMetaBuilder {
+ public:
+ SuperVBMetaBuilder();
+ SuperVBMetaBuilder(const int super_vbmeta_fd,
+ const std::map<std::string, std::string>& images_path);
+ android::base::Result<void> Build();
+ android::base::Result<std::string> ReadVBMetaImageFromFile(const std::string& file);
+ // It adds the vbmeta image in super_vbmeta and returns the index
+ // (which has the same meaning with vbmeta_index of VBMetaDescriptor).
+ android::base::Result<uint8_t> AddVBMetaImage(const std::string& vbmeta_name);
+ void DeleteVBMetaImage(const std::string& vbmeta_name);
+ std::unique_ptr<VBMetaTable> ExportVBMetaTable();
+ android::base::Result<void> ExportVBMetaTableToFile();
+ android::base::Result<void> ExportVBMetaImageToFile(const uint8_t vbmeta_index,
+ const std::string& vbmeta_image);
+
+ private:
+ android::base::Result<uint8_t> GetEmptySlot();
+
+ int super_vbmeta_fd_;
+ VBMetaTable table_;
+ // Maps vbmeta image name to vbmeta image file path.
+ std::map<std::string, std::string> images_path_;
+};
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/builder_test.cpp b/fs_mgr/libvbmeta/builder_test.cpp
new file mode 100644
index 0000000..9a015fd
--- /dev/null
+++ b/fs_mgr/libvbmeta/builder_test.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include "builder.h"
+#include "super_vbmeta_format.h"
+
+using android::base::Result;
+using android::fs_mgr::SuperVBMetaBuilder;
+
+TEST(BuilderTest, VBMetaTableBasic) {
+ std::unique_ptr<SuperVBMetaBuilder> builder = std::make_unique<SuperVBMetaBuilder>();
+ ASSERT_NE(builder, nullptr);
+
+ Result<uint8_t> vbmeta_index = builder->AddVBMetaImage("vbmeta" /* vbmeta_name */
+ );
+ EXPECT_TRUE(vbmeta_index);
+
+ Result<uint8_t> vbmeta_system_slot = builder->AddVBMetaImage("vbmeta_system" /* vbmeta_name */
+ );
+ EXPECT_TRUE(vbmeta_system_slot);
+
+ Result<uint8_t> vbmeta_vendor_slot = builder->AddVBMetaImage("vbmeta_vendor" /* vbmeta_name */
+ );
+ EXPECT_TRUE(vbmeta_vendor_slot);
+
+ builder->DeleteVBMetaImage("vbmeta_system" /* vbmeta_name */
+ );
+
+ Result<uint8_t> vbmeta_product_slot = builder->AddVBMetaImage("vbmeta_product" /* vbmeta_name */
+ );
+ EXPECT_TRUE(vbmeta_product_slot);
+
+ std::unique_ptr<VBMetaTable> table = builder->ExportVBMetaTable();
+ ASSERT_NE(table, nullptr);
+
+ // check for vbmeta table header
+ EXPECT_EQ(table->header.magic, SUPER_VBMETA_MAGIC);
+ EXPECT_EQ(table->header.major_version, SUPER_VBMETA_MAJOR_VERSION);
+ EXPECT_EQ(table->header.minor_version, SUPER_VBMETA_MINOR_VERSION);
+ EXPECT_EQ(table->header.header_size, SUPER_VBMETA_HEADER_SIZE);
+ EXPECT_EQ(table->header.total_size,
+ SUPER_VBMETA_HEADER_SIZE + SUPER_VBMETA_DESCRIPTOR_SIZE * 3 + 33);
+ EXPECT_EQ(table->header.descriptors_size, SUPER_VBMETA_DESCRIPTOR_SIZE * 3 + 33);
+
+ // Test for vbmeta table descriptors
+ EXPECT_EQ(table->descriptors.size(), 3);
+
+ EXPECT_EQ(table->descriptors[0].vbmeta_index, 0);
+ EXPECT_EQ(table->descriptors[0].vbmeta_name_length, 6);
+ for (int i = 0; i < sizeof(table->descriptors[0].reserved); i++)
+ EXPECT_EQ(table->descriptors[0].reserved[i], 0);
+ EXPECT_EQ(table->descriptors[0].vbmeta_name, "vbmeta");
+
+ EXPECT_EQ(table->descriptors[1].vbmeta_index, 2);
+ EXPECT_EQ(table->descriptors[1].vbmeta_name_length, 13);
+ for (int i = 0; i < sizeof(table->descriptors[1].reserved); i++)
+ EXPECT_EQ(table->descriptors[1].reserved[i], 0);
+ EXPECT_EQ(table->descriptors[1].vbmeta_name, "vbmeta_vendor");
+
+ EXPECT_EQ(table->descriptors[2].vbmeta_index, 1);
+ EXPECT_EQ(table->descriptors[2].vbmeta_name_length, 14);
+ for (int i = 0; i < sizeof(table->descriptors[2].reserved); i++)
+ EXPECT_EQ(table->descriptors[2].reserved[i], 0);
+ EXPECT_EQ(table->descriptors[2].vbmeta_name, "vbmeta_product");
+}
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/include/libvbmeta/libvbmeta.h b/fs_mgr/libvbmeta/include/libvbmeta/libvbmeta.h
new file mode 100644
index 0000000..ab7ba73
--- /dev/null
+++ b/fs_mgr/libvbmeta/include/libvbmeta/libvbmeta.h
@@ -0,0 +1,29 @@
+/*
+ * 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 <map>
+#include <string>
+
+namespace android {
+namespace fs_mgr {
+
+bool WriteToSuperVBMetaFile(const std::string& super_vbmeta_file,
+ const std::map<std::string, std::string>& images_path);
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/reader.cpp b/fs_mgr/libvbmeta/reader.cpp
new file mode 100644
index 0000000..212d186
--- /dev/null
+++ b/fs_mgr/libvbmeta/reader.cpp
@@ -0,0 +1,118 @@
+/*
+ * 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 "reader.h"
+
+#include <android-base/file.h>
+
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+
+namespace android {
+namespace fs_mgr {
+
+Result<void> LoadAndVerifySuperVBMetaHeader(const void* buffer, SuperVBMetaHeader* header) {
+ memcpy(header, buffer, sizeof(*header));
+
+ // Do basic validation of super vbmeta.
+ if (header->magic != SUPER_VBMETA_MAGIC) {
+ return Error() << "Super VBMeta has invalid magic value";
+ }
+
+ // Check that the version is compatible.
+ if (header->major_version != SUPER_VBMETA_MAJOR_VERSION ||
+ header->minor_version > SUPER_VBMETA_MINOR_VERSION) {
+ return Error() << "Super VBMeta has incompatible version";
+ }
+ return {};
+}
+
+void LoadVBMetaDescriptors(const void* buffer, uint32_t size,
+ std::vector<InternalVBMetaDescriptor>* descriptors) {
+ for (int p = 0; p < size;) {
+ InternalVBMetaDescriptor descriptor;
+ memcpy(&descriptor, (char*)buffer + p, SUPER_VBMETA_DESCRIPTOR_SIZE);
+ p += SUPER_VBMETA_DESCRIPTOR_SIZE;
+
+ descriptor.vbmeta_name = std::string((char*)buffer + p, descriptor.vbmeta_name_length);
+ p += descriptor.vbmeta_name_length;
+
+ descriptors->emplace_back(std::move(descriptor));
+ }
+}
+
+Result<void> ReadVBMetaTable(int fd, uint64_t offset, VBMetaTable* table) {
+ std::unique_ptr<uint8_t[]> header_buffer =
+ std::make_unique<uint8_t[]>(SUPER_VBMETA_HEADER_SIZE);
+ if (!android::base::ReadFullyAtOffset(fd, header_buffer.get(), SUPER_VBMETA_HEADER_SIZE,
+ offset)) {
+ return ErrnoError() << "Couldn't read super vbmeta header at offset " << offset;
+ }
+
+ Result<void> rv_header = LoadAndVerifySuperVBMetaHeader(header_buffer.get(), &table->header);
+ if (!rv_header) {
+ return rv_header;
+ }
+
+ const uint64_t descriptors_offset = offset + table->header.header_size;
+ std::unique_ptr<uint8_t[]> descriptors_buffer =
+ std::make_unique<uint8_t[]>(table->header.descriptors_size);
+ if (!android::base::ReadFullyAtOffset(fd, descriptors_buffer.get(),
+ table->header.descriptors_size, descriptors_offset)) {
+ return ErrnoError() << "Couldn't read super vbmeta descriptors at offset "
+ << descriptors_offset;
+ }
+
+ LoadVBMetaDescriptors(descriptors_buffer.get(), table->header.descriptors_size,
+ &table->descriptors);
+ return {};
+}
+
+Result<void> ReadPrimaryVBMetaTable(int fd, VBMetaTable* table) {
+ uint64_t offset = PRIMARY_SUPER_VBMETA_TABLE_OFFSET;
+ return ReadVBMetaTable(fd, offset, table);
+}
+
+Result<void> ReadBackupVBMetaTable(int fd, VBMetaTable* table) {
+ uint64_t offset = BACKUP_SUPER_VBMETA_TABLE_OFFSET;
+ return ReadVBMetaTable(fd, offset, table);
+}
+
+Result<std::string> ReadVBMetaImage(int fd, int slot) {
+ const uint64_t offset = 2 * SUPER_VBMETA_TABLE_MAX_SIZE + slot * VBMETA_IMAGE_MAX_SIZE;
+ std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(VBMETA_IMAGE_MAX_SIZE);
+ if (!android::base::ReadFullyAtOffset(fd, buffer.get(), VBMETA_IMAGE_MAX_SIZE, offset)) {
+ return ErrnoError() << "Couldn't read vbmeta image at offset " << offset;
+ }
+ return std::string(reinterpret_cast<char*>(buffer.get()), VBMETA_IMAGE_MAX_SIZE);
+}
+
+Result<void> ValidateVBMetaImage(int super_vbmeta_fd, int vbmeta_index,
+ const std::string& vbmeta_image) {
+ Result<std::string> content = ReadVBMetaImage(super_vbmeta_fd, vbmeta_index);
+ if (!content) {
+ return content.error();
+ }
+
+ if (vbmeta_image != content.value()) {
+ return Error() << "VBMeta Image in Super VBMeta differ from the original one.";
+ }
+ return {};
+}
+
+} // namespace fs_mgr
+} // namespace android
diff --git a/fs_mgr/libvbmeta/reader.h b/fs_mgr/libvbmeta/reader.h
new file mode 100644
index 0000000..f0997ff
--- /dev/null
+++ b/fs_mgr/libvbmeta/reader.h
@@ -0,0 +1,34 @@
+/*
+ * 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 <android-base/result.h>
+
+#include "super_vbmeta_format.h"
+
+namespace android {
+namespace fs_mgr {
+
+android::base::Result<void> ReadPrimaryVBMetaTable(int fd, VBMetaTable* table);
+android::base::Result<void> ReadBackupVBMetaTable(int fd, VBMetaTable* table);
+android::base::Result<std::string> ReadVBMetaImage(int fd, int slot);
+
+android::base::Result<void> ValidateVBMetaImage(int super_vbmeta_fd, int vbmeta_index,
+ const std::string& vbmeta_image);
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/super_vbmeta_format.h b/fs_mgr/libvbmeta/super_vbmeta_format.h
new file mode 100644
index 0000000..c62a2dd
--- /dev/null
+++ b/fs_mgr/libvbmeta/super_vbmeta_format.h
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+/* This .h file is intended for CPP clients (usually fastbootd, recovery and update_engine) */
+
+#pragma once
+
+#include <string>
+#include <vector>
+
+#include "super_vbmeta_format_c.h"
+
+struct InternalVBMetaDescriptor : VBMetaDescriptor {
+ /* 64: The vbmeta image's name */
+ std::string vbmeta_name;
+};
+
+struct VBMetaTable {
+ SuperVBMetaHeader header;
+ std::vector<InternalVBMetaDescriptor> descriptors;
+};
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/super_vbmeta_format_c.h b/fs_mgr/libvbmeta/super_vbmeta_format_c.h
new file mode 100644
index 0000000..6d79801
--- /dev/null
+++ b/fs_mgr/libvbmeta/super_vbmeta_format_c.h
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+/* This .h file is intended for C clients (usually bootloader). */
+
+#pragma once
+
+#include <stdint.h>
+
+/* Magic signature for super vbmeta. */
+#define SUPER_VBMETA_MAGIC 0x5356424d
+
+/* Current super vbmeta version. */
+#define SUPER_VBMETA_MAJOR_VERSION 1
+#define SUPER_VBMETA_MINOR_VERSION 0
+
+/* super vbmeta size. */
+#define SUPER_VBMETA_HEADER_SIZE sizeof(SuperVBMetaHeader)
+#define SUPER_VBMETA_DESCRIPTOR_SIZE sizeof(VBMetaDescriptor)
+#define SUPER_VBMETA_TABLE_MAX_SIZE 2048
+
+/* super vbmeta offset. */
+#define PRIMARY_SUPER_VBMETA_TABLE_OFFSET 0
+#define BACKUP_SUPER_VBMETA_TABLE_OFFSET SUPER_VBMETA_TABLE_MAX_SIZE
+
+/* restriction of vbmeta image */
+#define VBMETA_IMAGE_MAX_NUM 32
+#define VBMETA_IMAGE_MAX_SIZE 64 * 1024
+
+/* Binary format of the super vbmeta image.
+ *
+ * The super vbmeta image consists of two blocks:
+ *
+ * +------------------------------------------+
+ * | Super VBMeta Table - fixed size |
+ * +------------------------------------------+
+ * | Backup Super VBMeta Table - fixed size |
+ * +------------------------------------------+
+ * | VBMeta Images - fixed size |
+ * +------------------------------------------+
+ *
+ * The "Super VBMeta Table" records the offset
+ * and the size of each vbmeta_partition within
+ * /super_vbmeta.
+ *
+ * The "VBMeta Image" is copied from each vbmeta_partition
+ * and filled with 0 until 64K bytes.
+ *
+ * The super vbmeta table consists of two blocks:
+ *
+ * +-----------------------------------------+
+ * | Header data - fixed size |
+ * +-----------------------------------------+
+ * | VBMeta descriptors - variable size |
+ * +-----------------------------------------+
+ *
+ * The "Header data" block is described by the following struct and
+ * is always 128 bytes long.
+ *
+ * The "VBMeta descriptor" is |descriptors_size| + |vbmeta_name_length|
+ * bytes long. It contains the offset and size for each vbmeta image
+ * and is followed by |vbmeta_name_length| bytes of the partition name
+ * (UTF-8 encoded).
+ */
+
+typedef struct SuperVBMetaHeader {
+ /* 0: Magic signature (SUPER_VBMETA_MAGIC). */
+ uint32_t magic;
+
+ /* 4: Major version. Version number required to read this super vbmeta. If the version is not
+ * equal to the library version, the super vbmeta should be considered incompatible.
+ */
+ uint16_t major_version;
+
+ /* 6: Minor version. A library supporting newer features should be able to
+ * read super vbmeta with an older minor version. However, an older library
+ * should not support reading super vbmeta if its minor version is higher.
+ */
+ uint16_t minor_version;
+
+ /* 8: The size of this header struct. */
+ uint32_t header_size;
+
+ /* 12: The size of this super vbmeta table. */
+ uint32_t total_size;
+
+ /* 16: SHA256 checksum of this super vbmeta table, with this field set to 0. */
+ uint8_t checksum[32];
+
+ /* 48: The size of the vbmeta table descriptors. */
+ uint32_t descriptors_size;
+
+ /* 52: mark which slot is in use. */
+ uint32_t in_use = 0;
+
+ /* 56: reserved for other usage, filled with 0. */
+ uint8_t reserved[72];
+} __attribute__((packed)) SuperVBMetaHeader;
+
+typedef struct VBMetaDescriptor {
+ /* 0: The slot number of the vbmeta image. */
+ uint8_t vbmeta_index;
+
+ /* 12: The length of the vbmeta image name. */
+ uint32_t vbmeta_name_length;
+
+ /* 16: Space reserved for other usage, filled with 0. */
+ uint8_t reserved[48];
+} __attribute__((packed)) VBMetaDescriptor;
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/super_vbmeta_test.cpp b/fs_mgr/libvbmeta/super_vbmeta_test.cpp
new file mode 100644
index 0000000..6b4fc5d
--- /dev/null
+++ b/fs_mgr/libvbmeta/super_vbmeta_test.cpp
@@ -0,0 +1,191 @@
+/*
+ * 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 <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/file.h>
+#include <gtest/gtest.h>
+#include <openssl/sha.h>
+#include <sparse/sparse.h>
+
+#include "reader.h"
+#include "super_vbmeta_format.h"
+#include "utility.h"
+#include "writer.h"
+
+#define FAKE_DATA_SIZE 40960
+#define FAKE_PARTITION_SIZE FAKE_DATA_SIZE * 25
+
+using android::base::Result;
+using android::fs_mgr::GetFileSize;
+using android::fs_mgr::ReadVBMetaImage;
+using SparsePtr = std::unique_ptr<sparse_file, decltype(&sparse_file_destroy)>;
+
+void GeneratePartitionImage(int fd, const std::string& file_name,
+ const std::string& partition_name) {
+ std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(FAKE_DATA_SIZE);
+ for (size_t c = 0; c < FAKE_DATA_SIZE; c++) {
+ buffer[c] = uint8_t(c);
+ }
+
+ SparsePtr file(sparse_file_new(512 /* block size */, FAKE_DATA_SIZE), sparse_file_destroy);
+ EXPECT_TRUE(file);
+ EXPECT_EQ(0, sparse_file_add_data(file.get(), buffer.get(), FAKE_DATA_SIZE,
+ 0 /* offset in blocks */));
+ EXPECT_EQ(0, sparse_file_write(file.get(), fd, false /* gz */, true /* sparse */,
+ false /* crc */));
+
+ std::stringstream cmd;
+ cmd << "avbtool add_hashtree_footer"
+ << " --image " << file_name << " --partition_name " << partition_name
+ << " --partition_size " << FAKE_PARTITION_SIZE << " --algorithm SHA256_RSA2048"
+ << " --key external/avb/test/data/testkey_rsa2048.pem";
+
+ int rc = system(cmd.str().c_str());
+ EXPECT_TRUE(WIFEXITED(rc));
+ EXPECT_EQ(WEXITSTATUS(rc), 0);
+}
+
+void GenerateVBMetaImage(const std::string& vbmeta_file_name,
+ const std::string& include_file_name) {
+ std::stringstream cmd;
+ cmd << "avbtool make_vbmeta_image"
+ << " --output " << vbmeta_file_name << " --include_descriptors_from_image "
+ << include_file_name;
+
+ int rc = system(cmd.str().c_str());
+ EXPECT_TRUE(WIFEXITED(rc));
+ EXPECT_EQ(WEXITSTATUS(rc), 0);
+}
+
+std::string ReadVBMetaImageFromFile(const std::string& file) {
+ android::base::unique_fd fd(open(file.c_str(), O_RDONLY | O_CLOEXEC));
+ EXPECT_GT(fd, 0);
+ Result<uint64_t> file_size = GetFileSize(fd);
+ EXPECT_TRUE(file_size);
+ std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(VBMETA_IMAGE_MAX_SIZE);
+ EXPECT_TRUE(android::base::ReadFully(fd, buffer.get(), file_size.value()));
+ return std::string(reinterpret_cast<char*>(buffer.get()), VBMETA_IMAGE_MAX_SIZE);
+}
+
+TEST(VBMetaTableTest, VBMetaTableBasic) {
+ TemporaryDir td;
+
+ // Generate Partition Image
+ TemporaryFile system_tf(std::string(td.path));
+ std::string system_path(system_tf.path);
+ GeneratePartitionImage(system_tf.fd, system_path, "system");
+ system_tf.release();
+
+ TemporaryFile vendor_tf(std::string(td.path));
+ std::string vendor_path(vendor_tf.path);
+ GeneratePartitionImage(vendor_tf.fd, vendor_path, "vendor");
+ vendor_tf.release();
+
+ TemporaryFile product_tf(std::string(td.path));
+ std::string product_path(product_tf.path);
+ GeneratePartitionImage(product_tf.fd, product_path, "product");
+ product_tf.release();
+
+ // Generate VBMeta Image
+ std::string vbmeta_system_path(td.path);
+ vbmeta_system_path.append("/vbmeta_system.img");
+ GenerateVBMetaImage(vbmeta_system_path, system_path);
+
+ std::string vbmeta_vendor_path(td.path);
+ vbmeta_vendor_path.append("/vbmeta_vendor.img");
+ GenerateVBMetaImage(vbmeta_vendor_path, vendor_path);
+
+ std::string vbmeta_product_path(td.path);
+ vbmeta_product_path.append("/vbmeta_product.img");
+ GenerateVBMetaImage(vbmeta_product_path, product_path);
+
+ // Generate Super VBMeta Image
+ std::string super_vbmeta_path(td.path);
+ super_vbmeta_path.append("/super_vbmeta.img");
+
+ std::stringstream cmd;
+ cmd << "vbmake"
+ << " --image "
+ << "vbmeta_system"
+ << "=" << vbmeta_system_path << " --image "
+ << "vbmeta_vendor"
+ << "=" << vbmeta_vendor_path << " --image "
+ << "vbmeta_product"
+ << "=" << vbmeta_product_path << " --output=" << super_vbmeta_path;
+
+ int rc = system(cmd.str().c_str());
+ ASSERT_TRUE(WIFEXITED(rc));
+ ASSERT_EQ(WEXITSTATUS(rc), 0);
+
+ android::base::unique_fd fd(open(super_vbmeta_path.c_str(), O_RDONLY | O_CLOEXEC));
+ EXPECT_GT(fd, 0);
+
+ // Check the size of vbmeta table
+ Result<uint64_t> super_vbmeta_size = GetFileSize(fd);
+ EXPECT_TRUE(super_vbmeta_size);
+ EXPECT_EQ(super_vbmeta_size.value(),
+ SUPER_VBMETA_TABLE_MAX_SIZE * 2 + VBMETA_IMAGE_MAX_SIZE * 3);
+
+ // Check Primary vbmeta table is equal to Backup one
+ VBMetaTable table;
+ EXPECT_TRUE(android::fs_mgr::ReadPrimaryVBMetaTable(fd, &table));
+ VBMetaTable table_backup;
+ EXPECT_TRUE(android::fs_mgr::ReadBackupVBMetaTable(fd, &table_backup));
+ EXPECT_EQ(android::fs_mgr::SerializeVBMetaTable(table),
+ android::fs_mgr::SerializeVBMetaTable(table_backup));
+
+ // Check vbmeta table Header Checksum
+ std::string serial_table = android::fs_mgr::SerializeVBMetaTable(table);
+ std::string serial_removed_checksum(serial_table);
+ // Replace checksum 32 bytes (starts at 16th byte) with 0
+ serial_removed_checksum.replace(16, 32, 32, 0);
+ uint8_t test_checksum[32];
+ ::SHA256(reinterpret_cast<const uint8_t*>(serial_removed_checksum.c_str()),
+ table.header.total_size, &test_checksum[0]);
+ EXPECT_EQ(memcmp(table.header.checksum, test_checksum, 32), 0);
+
+ // Check vbmeta table descriptors and vbmeta images
+ EXPECT_EQ(table.descriptors.size(), 3);
+
+ EXPECT_EQ(table.descriptors[0].vbmeta_index, 0);
+ EXPECT_EQ(table.descriptors[0].vbmeta_name_length, 14);
+ EXPECT_EQ(table.descriptors[0].vbmeta_name, "vbmeta_product");
+ Result<std::string> vbmeta_product_content = ReadVBMetaImage(fd, 0);
+ EXPECT_TRUE(vbmeta_product_content);
+ EXPECT_EQ(ReadVBMetaImageFromFile(vbmeta_product_path), vbmeta_product_content.value());
+
+ EXPECT_EQ(table.descriptors[1].vbmeta_index, 1);
+ EXPECT_EQ(table.descriptors[1].vbmeta_name_length, 13);
+ EXPECT_EQ(table.descriptors[1].vbmeta_name, "vbmeta_system");
+ Result<std::string> vbmeta_system_content = ReadVBMetaImage(fd, 1);
+ EXPECT_TRUE(vbmeta_system_content);
+ EXPECT_EQ(ReadVBMetaImageFromFile(vbmeta_system_path), vbmeta_system_content.value());
+
+ EXPECT_EQ(table.descriptors[2].vbmeta_index, 2);
+ EXPECT_EQ(table.descriptors[2].vbmeta_name_length, 13);
+ EXPECT_EQ(table.descriptors[2].vbmeta_name, "vbmeta_vendor");
+ Result<std::string> vbmeta_vendor_content = ReadVBMetaImage(fd, 2);
+ EXPECT_TRUE(vbmeta_vendor_content);
+ EXPECT_EQ(ReadVBMetaImageFromFile(vbmeta_vendor_path), vbmeta_vendor_content.value());
+}
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/utility.cpp b/fs_mgr/libvbmeta/utility.cpp
new file mode 100644
index 0000000..c184227
--- /dev/null
+++ b/fs_mgr/libvbmeta/utility.cpp
@@ -0,0 +1,47 @@
+/*
+ * 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 "utility.h"
+
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "super_vbmeta_format.h"
+
+using android::base::ErrnoError;
+using android::base::Error;
+using android::base::Result;
+
+namespace android {
+namespace fs_mgr {
+
+Result<uint64_t> GetFileSize(int fd) {
+ struct stat sb;
+ if (fstat(fd, &sb) == -1) {
+ return ErrnoError() << "Couldn't get the file size";
+ }
+ return sb.st_size;
+}
+
+uint64_t IndexOffset(const uint8_t vbmeta_index) {
+ /* There are primary and backup vbmeta table in super_vbmeta,
+ so SUPER_VBMETA_TABLE_MAX_SIZE is counted twice. */
+ return 2 * SUPER_VBMETA_TABLE_MAX_SIZE + vbmeta_index * VBMETA_IMAGE_MAX_SIZE;
+}
+
+} // namespace fs_mgr
+} // namespace android
diff --git a/fs_mgr/libvbmeta/utility.h b/fs_mgr/libvbmeta/utility.h
new file mode 100644
index 0000000..91db0ad
--- /dev/null
+++ b/fs_mgr/libvbmeta/utility.h
@@ -0,0 +1,37 @@
+/*
+ * 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 <android-base/logging.h>
+#include <android-base/result.h>
+
+#define VBMETA_TAG "[libvbmeta]"
+#define LWARN LOG(WARNING) << VBMETA_TAG
+#define LINFO LOG(INFO) << VBMETA_TAG
+#define LERROR LOG(ERROR) << VBMETA_TAG
+#define PWARNING PLOG(WARNING) << VBMETA_TAG
+#define PERROR PLOG(ERROR) << VBMETA_TAG
+
+namespace android {
+namespace fs_mgr {
+
+android::base::Result<uint64_t> GetFileSize(int fd);
+
+uint64_t IndexOffset(const uint8_t vbmeta_index);
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/writer.cpp b/fs_mgr/libvbmeta/writer.cpp
new file mode 100644
index 0000000..fc0e0fb
--- /dev/null
+++ b/fs_mgr/libvbmeta/writer.cpp
@@ -0,0 +1,81 @@
+/*
+ * 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 "writer.h"
+
+#include <android-base/file.h>
+
+#include "utility.h"
+
+using android::base::ErrnoError;
+using android::base::Result;
+
+namespace android {
+namespace fs_mgr {
+
+std::string SerializeVBMetaTable(const VBMetaTable& input) {
+ std::string table;
+ table.append(reinterpret_cast<const char*>(&input.header), SUPER_VBMETA_HEADER_SIZE);
+
+ for (const auto& desc : input.descriptors) {
+ table.append(reinterpret_cast<const char*>(&desc), SUPER_VBMETA_DESCRIPTOR_SIZE);
+ table.append(desc.vbmeta_name);
+ }
+
+ // Ensure the size of vbmeta table is SUPER_VBMETA_TABLE_MAX_SIZE
+ table.resize(SUPER_VBMETA_TABLE_MAX_SIZE, '\0');
+
+ return table;
+}
+
+Result<void> WritePrimaryVBMetaTable(int fd, const std::string& table) {
+ const uint64_t offset = PRIMARY_SUPER_VBMETA_TABLE_OFFSET;
+ if (lseek(fd, offset, SEEK_SET) < 0) {
+ return ErrnoError() << __PRETTY_FUNCTION__ << " lseek failed";
+ }
+
+ if (!android::base::WriteFully(fd, table.data(), table.size())) {
+ return ErrnoError() << "Failed to write primary vbmeta table at offset " << offset;
+ }
+ return {};
+}
+
+Result<void> WriteBackupVBMetaTable(int fd, const std::string& table) {
+ const uint64_t offset = BACKUP_SUPER_VBMETA_TABLE_OFFSET;
+ if (lseek(fd, offset, SEEK_SET) < 0) {
+ return ErrnoError() << __PRETTY_FUNCTION__ << " lseek failed";
+ }
+
+ if (!android::base::WriteFully(fd, table.data(), table.size())) {
+ return ErrnoError() << "Failed to write backup vbmeta table at offset " << offset;
+ }
+ return {};
+}
+
+Result<void> WriteVBMetaImage(int fd, const uint8_t slot_number, const std::string& vbmeta_image) {
+ const uint64_t offset = IndexOffset(slot_number);
+ if (lseek(fd, offset, SEEK_SET) < 0) {
+ return ErrnoError() << __PRETTY_FUNCTION__ << " lseek failed";
+ }
+
+ if (!android::base::WriteFully(fd, vbmeta_image.data(), vbmeta_image.size())) {
+ return ErrnoError() << "Failed to write vbmeta image at offset " << offset;
+ }
+ return {};
+}
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/fs_mgr/libvbmeta/writer.h b/fs_mgr/libvbmeta/writer.h
new file mode 100644
index 0000000..f8eed36
--- /dev/null
+++ b/fs_mgr/libvbmeta/writer.h
@@ -0,0 +1,36 @@
+/*
+ * 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 <android-base/result.h>
+
+#include "super_vbmeta_format.h"
+
+namespace android {
+namespace fs_mgr {
+
+std::string SerializeVBMetaTable(const VBMetaTable& input);
+
+android::base::Result<void> WritePrimaryVBMetaTable(int fd, const std::string& table);
+android::base::Result<void> WriteBackupVBMetaTable(int fd, const std::string& table);
+android::base::Result<void> WriteVBMetaImage(int fd, const uint8_t slot_number,
+ const std::string& vbmeta_image);
+
+} // namespace fs_mgr
+} // namespace android
\ No newline at end of file
diff --git a/init/Android.bp b/init/Android.bp
index 9714014..b601075 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -62,7 +62,6 @@
},
},
static_libs: [
- "libseccomp_policy",
"libavb",
"libc++fs",
"libcgrouprc_format",
diff --git a/init/Android.mk b/init/Android.mk
index 54163fa..8f58437 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -92,7 +92,6 @@
liblogwrap \
libext4_utils \
libfscrypt \
- libseccomp_policy \
libcrypto_utils \
libsparse \
libavb \
diff --git a/init/action_parser.cpp b/init/action_parser.cpp
index ff20e43..9736824 100644
--- a/init/action_parser.cpp
+++ b/init/action_parser.cpp
@@ -121,13 +121,8 @@
}
Subcontext* action_subcontext = nullptr;
- if (subcontexts_) {
- for (auto& subcontext : *subcontexts_) {
- if (StartsWith(filename, subcontext.path_prefix())) {
- action_subcontext = &subcontext;
- break;
- }
- }
+ if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
+ action_subcontext = subcontext_;
}
std::string event_trigger;
diff --git a/init/action_parser.h b/init/action_parser.h
index 2fe9983..3000132 100644
--- a/init/action_parser.h
+++ b/init/action_parser.h
@@ -30,8 +30,8 @@
class ActionParser : public SectionParser {
public:
- ActionParser(ActionManager* action_manager, std::vector<Subcontext>* subcontexts)
- : action_manager_(action_manager), subcontexts_(subcontexts), action_(nullptr) {}
+ ActionParser(ActionManager* action_manager, Subcontext* subcontext)
+ : action_manager_(action_manager), subcontext_(subcontext), action_(nullptr) {}
Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
int line) override;
Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
@@ -39,7 +39,7 @@
private:
ActionManager* action_manager_;
- std::vector<Subcontext>* subcontexts_;
+ Subcontext* subcontext_;
std::unique_ptr<Action> action_;
};
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index 6b4216f..4a1bc5a 100644
--- a/init/first_stage_mount.cpp
+++ b/init/first_stage_mount.cpp
@@ -77,8 +77,9 @@
bool InitDevices();
protected:
- ListenerAction HandleBlockDevice(const std::string& name, const Uevent&);
- bool InitRequiredDevices();
+ ListenerAction HandleBlockDevice(const std::string& name, const Uevent&,
+ std::set<std::string>* required_devices);
+ bool InitRequiredDevices(std::set<std::string> devices);
bool InitMappedDevice(const std::string& verity_device);
bool InitDeviceMapper();
bool CreateLogicalPartitions();
@@ -89,14 +90,14 @@
bool TrySwitchSystemAsRoot();
bool TrySkipMountingPartitions();
bool IsDmLinearEnabled();
- bool GetDmLinearMetadataDevice();
+ void GetDmLinearMetadataDevice(std::set<std::string>* devices);
bool InitDmLinearBackingDevices(const android::fs_mgr::LpMetadata& metadata);
void UseGsiIfPresent();
- ListenerAction UeventCallback(const Uevent& uevent);
+ ListenerAction UeventCallback(const Uevent& uevent, std::set<std::string>* required_devices);
// Pure virtual functions.
- virtual bool GetDmVerityDevices() = 0;
+ virtual bool GetDmVerityDevices(std::set<std::string>* devices) = 0;
virtual bool SetUpDmVerity(FstabEntry* fstab_entry) = 0;
bool need_dm_verity_;
@@ -104,7 +105,6 @@
Fstab fstab_;
std::string lp_metadata_partition_;
- std::set<std::string> required_devices_partition_names_;
std::string super_partition_name_;
std::unique_ptr<DeviceHandler> device_handler_;
UeventListener uevent_listener_;
@@ -116,7 +116,7 @@
~FirstStageMountVBootV1() override = default;
protected:
- bool GetDmVerityDevices() override;
+ bool GetDmVerityDevices(std::set<std::string>* devices) override;
bool SetUpDmVerity(FstabEntry* fstab_entry) override;
};
@@ -128,7 +128,7 @@
~FirstStageMountVBootV2() override = default;
protected:
- bool GetDmVerityDevices() override;
+ bool GetDmVerityDevices(std::set<std::string>* devices) override;
bool SetUpDmVerity(FstabEntry* fstab_entry) override;
bool InitAvbHandle();
@@ -252,7 +252,13 @@
}
bool FirstStageMount::InitDevices() {
- return GetDmLinearMetadataDevice() && GetDmVerityDevices() && InitRequiredDevices();
+ std::set<std::string> devices;
+ GetDmLinearMetadataDevice(&devices);
+
+ if (!GetDmVerityDevices(&devices)) {
+ return false;
+ }
+ return InitRequiredDevices(std::move(devices));
}
bool FirstStageMount::IsDmLinearEnabled() {
@@ -262,45 +268,46 @@
return false;
}
-bool FirstStageMount::GetDmLinearMetadataDevice() {
+void FirstStageMount::GetDmLinearMetadataDevice(std::set<std::string>* devices) {
// Add any additional devices required for dm-linear mappings.
if (!IsDmLinearEnabled()) {
- return true;
+ return;
}
- required_devices_partition_names_.emplace(super_partition_name_);
- return true;
+ devices->emplace(super_partition_name_);
}
-// Creates devices with uevent->partition_name matching one in the member variable
-// 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() {
+// Creates devices with uevent->partition_name matching ones in the given set.
+// Found partitions will then be removed from it for the subsequent member
+// function to check which devices are NOT created.
+bool FirstStageMount::InitRequiredDevices(std::set<std::string> devices) {
if (!InitDeviceMapper()) {
return false;
}
- if (required_devices_partition_names_.empty()) {
+ if (devices.empty()) {
return true;
}
- auto uevent_callback = [this](const Uevent& uevent) { return UeventCallback(uevent); };
+ auto uevent_callback = [&, this](const Uevent& uevent) {
+ return UeventCallback(uevent, &devices);
+ };
uevent_listener_.RegenerateUevents(uevent_callback);
- // UeventCallback() will remove found partitions from required_devices_partition_names_.
- // So if it isn't empty here, it means some partitions are not found.
- if (!required_devices_partition_names_.empty()) {
+ // UeventCallback() will remove found partitions from |devices|. So if it
+ // isn't empty here, it means some partitions are not found.
+ if (!devices.empty()) {
LOG(INFO) << __PRETTY_FUNCTION__
<< ": partition(s) not found in /sys, waiting for their uevent(s): "
- << android::base::Join(required_devices_partition_names_, ", ");
+ << android::base::Join(devices, ", ");
Timer t;
uevent_listener_.Poll(uevent_callback, 10s);
LOG(INFO) << "Wait for partitions returned after " << t;
}
- if (!required_devices_partition_names_.empty()) {
+ if (!devices.empty()) {
LOG(ERROR) << __PRETTY_FUNCTION__ << ": partition(s) not found after polling timeout: "
- << android::base::Join(required_devices_partition_names_, ", ");
+ << android::base::Join(devices, ", ");
return false;
}
@@ -333,27 +340,20 @@
}
bool FirstStageMount::InitDmLinearBackingDevices(const android::fs_mgr::LpMetadata& metadata) {
+ std::set<std::string> devices;
+
auto partition_names = android::fs_mgr::GetBlockDevicePartitionNames(metadata);
for (const auto& partition_name : partition_names) {
// The super partition was found in the earlier pass.
if (partition_name == super_partition_name_) {
continue;
}
- required_devices_partition_names_.emplace(partition_name);
+ devices.emplace(partition_name);
}
- if (required_devices_partition_names_.empty()) {
+ if (devices.empty()) {
return true;
}
-
- auto uevent_callback = [this](const Uevent& uevent) { return UeventCallback(uevent); };
- uevent_listener_.RegenerateUevents(uevent_callback);
-
- if (!required_devices_partition_names_.empty()) {
- LOG(ERROR) << __PRETTY_FUNCTION__ << ": partition(s) not found after polling timeout: "
- << android::base::Join(required_devices_partition_names_, ", ");
- return false;
- }
- return true;
+ return InitRequiredDevices(std::move(devices));
}
bool FirstStageMount::CreateLogicalPartitions() {
@@ -372,6 +372,11 @@
return false;
}
if (sm->NeedSnapshotsInFirstStageMount()) {
+ // When COW images are present for snapshots, they are stored on
+ // the data partition.
+ if (!InitRequiredDevices({"userdata"})) {
+ return false;
+ }
return sm->CreateLogicalAndSnapshotPartitions(lp_metadata_partition_);
}
}
@@ -387,20 +392,21 @@
return android::fs_mgr::CreateLogicalPartitions(*metadata.get(), lp_metadata_partition_);
}
-ListenerAction FirstStageMount::HandleBlockDevice(const std::string& name, const Uevent& uevent) {
+ListenerAction FirstStageMount::HandleBlockDevice(const std::string& name, const Uevent& uevent,
+ std::set<std::string>* required_devices) {
// Matches partition name to create device nodes.
// Both required_devices_partition_names_ and uevent->partition_name have A/B
// suffix when A/B is used.
- auto iter = required_devices_partition_names_.find(name);
- if (iter != required_devices_partition_names_.end()) {
+ auto iter = required_devices->find(name);
+ if (iter != required_devices->end()) {
LOG(VERBOSE) << __PRETTY_FUNCTION__ << ": found partition: " << *iter;
if (IsDmLinearEnabled() && name == super_partition_name_) {
std::vector<std::string> links = device_handler_->GetBlockDeviceSymlinks(uevent);
lp_metadata_partition_ = links[0];
}
- required_devices_partition_names_.erase(iter);
+ required_devices->erase(iter);
device_handler_->HandleUevent(uevent);
- if (required_devices_partition_names_.empty()) {
+ if (required_devices->empty()) {
return ListenerAction::kStop;
} else {
return ListenerAction::kContinue;
@@ -409,18 +415,19 @@
return ListenerAction::kContinue;
}
-ListenerAction FirstStageMount::UeventCallback(const Uevent& uevent) {
+ListenerAction FirstStageMount::UeventCallback(const Uevent& uevent,
+ std::set<std::string>* required_devices) {
// Ignores everything that is not a block device.
if (uevent.subsystem != "block") {
return ListenerAction::kContinue;
}
if (!uevent.partition_name.empty()) {
- return HandleBlockDevice(uevent.partition_name, uevent);
+ return HandleBlockDevice(uevent.partition_name, uevent, required_devices);
} else {
size_t base_idx = uevent.path.rfind('/');
if (base_idx != std::string::npos) {
- return HandleBlockDevice(uevent.path.substr(base_idx + 1), uevent);
+ return HandleBlockDevice(uevent.path.substr(base_idx + 1), uevent, required_devices);
}
}
// Not found a partition or find an unneeded partition, continue to find others.
@@ -577,17 +584,7 @@
const auto devices = fs_mgr_overlayfs_required_devices(&fstab_);
for (auto const& device : devices) {
if (android::base::StartsWith(device, "/dev/block/by-name/")) {
- required_devices_partition_names_.emplace(basename(device.c_str()));
- auto uevent_callback = [this](const Uevent& uevent) { return UeventCallback(uevent); };
- uevent_listener_.RegenerateUevents(uevent_callback);
- if (!required_devices_partition_names_.empty()) {
- uevent_listener_.Poll(uevent_callback, 10s);
- if (!required_devices_partition_names_.empty()) {
- LOG(ERROR) << __PRETTY_FUNCTION__
- << ": partition(s) not found after polling timeout: "
- << android::base::Join(required_devices_partition_names_, ", ");
- }
- }
+ InitRequiredDevices({basename(device.c_str())});
} else {
InitMappedDevice(device);
}
@@ -641,7 +638,7 @@
gsi_not_on_userdata_ = (super_name != "userdata");
}
-bool FirstStageMountVBootV1::GetDmVerityDevices() {
+bool FirstStageMountVBootV1::GetDmVerityDevices(std::set<std::string>* devices) {
need_dm_verity_ = false;
for (const auto& fstab_entry : fstab_) {
@@ -660,7 +657,7 @@
// Notes that fstab_rec->blk_device has A/B suffix updated by fs_mgr when A/B is used.
for (const auto& fstab_entry : fstab_) {
if (!fstab_entry.fs_mgr_flags.logical) {
- required_devices_partition_names_.emplace(basename(fstab_entry.blk_device.c_str()));
+ devices->emplace(basename(fstab_entry.blk_device.c_str()));
}
}
@@ -711,7 +708,7 @@
}
}
-bool FirstStageMountVBootV2::GetDmVerityDevices() {
+bool FirstStageMountVBootV2::GetDmVerityDevices(std::set<std::string>* devices) {
need_dm_verity_ = false;
std::set<std::string> logical_partitions;
@@ -725,7 +722,7 @@
// Don't try to find logical partitions via uevent regeneration.
logical_partitions.emplace(basename(fstab_entry.blk_device.c_str()));
} else {
- required_devices_partition_names_.emplace(basename(fstab_entry.blk_device.c_str()));
+ devices->emplace(basename(fstab_entry.blk_device.c_str()));
}
}
@@ -742,11 +739,11 @@
if (logical_partitions.count(partition_name)) {
continue;
}
- // required_devices_partition_names_ is of type std::set so it's not an issue
- // to emplace a partition twice. e.g., /vendor might be in both places:
+ // devices is of type std::set so it's not an issue to emplace a
+ // partition twice. e.g., /vendor might be in both places:
// - device_tree_vbmeta_parts_ = "vbmeta,boot,system,vendor"
// - mount_fstab_recs_: /vendor_a
- required_devices_partition_names_.emplace(partition_name);
+ devices->emplace(partition_name);
}
}
return true;
diff --git a/init/init.cpp b/init/init.cpp
index 53b065f..ad31fa0 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -19,7 +19,6 @@
#include <dirent.h>
#include <fcntl.h>
#include <pthread.h>
-#include <seccomp_policy.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
@@ -104,7 +103,7 @@
static bool do_shutdown = false;
static bool load_debug_prop = false;
-static std::vector<Subcontext>* subcontexts;
+static std::unique_ptr<Subcontext> subcontext;
void DumpState() {
ServiceList::GetInstance().DumpState();
@@ -114,9 +113,10 @@
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
Parser parser;
- parser.AddSectionParser(
- "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
- parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
+ parser.AddSectionParser("service", std::make_unique<ServiceParser>(
+ &service_list, subcontext.get(), std::nullopt));
+ parser.AddSectionParser("on",
+ std::make_unique<ActionParser>(&action_manager, subcontext.get()));
parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
return parser;
@@ -126,8 +126,8 @@
Parser CreateServiceOnlyParser(ServiceList& service_list) {
Parser parser;
- parser.AddSectionParser(
- "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
+ parser.AddSectionParser("service", std::make_unique<ServiceParser>(
+ &service_list, subcontext.get(), std::nullopt));
return parser;
}
@@ -581,15 +581,6 @@
}
}
-static void GlobalSeccomp() {
- import_kernel_cmdline(false, [](const std::string& key, const std::string& value,
- bool in_qemu) {
- if (key == "androidboot.seccomp" && value == "global" && !set_global_seccomp_filter()) {
- LOG(FATAL) << "Failed to globally enable seccomp!";
- }
- });
-}
-
static void UmountDebugRamdisk() {
if (umount("/debug_ramdisk") != 0) {
LOG(ERROR) << "Failed to umount /debug_ramdisk";
@@ -691,9 +682,6 @@
LOG(ERROR) << "Unable to write -1000 to /proc/1/oom_score_adj: " << result.error();
}
- // Enable seccomp if global boot option was passed (otherwise it is enabled in zygote).
- GlobalSeccomp();
-
// Set up a session keyring that all processes will have access to. It
// will hold things like FBE encryption keys. No process should override
// its session keyring.
@@ -762,7 +750,7 @@
PLOG(FATAL) << "SetupMountNamespaces failed";
}
- subcontexts = InitializeSubcontexts();
+ subcontext = InitializeSubcontext();
ActionManager& am = ActionManager::GetInstance();
ServiceList& sm = ServiceList::GetInstance();
diff --git a/init/property_service.cpp b/init/property_service.cpp
index c18decc..f5d1143 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -530,7 +530,7 @@
uint32_t result = 0;
ucred cr = {.pid = 1, .uid = 0, .gid = 0};
std::string error;
- result = HandlePropertySet(name, value, kInitContext.c_str(), cr, nullptr, &error);
+ result = HandlePropertySet(name, value, kInitContext, cr, nullptr, &error);
if (result != PROP_SUCCESS) {
LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
}
@@ -645,11 +645,16 @@
char *key, *value, *eol, *sol, *tmp, *fn;
size_t flen = 0;
- const char* context = kInitContext.c_str();
+ static constexpr const char* const kVendorPathPrefixes[2] = {
+ "/vendor",
+ "/odm",
+ };
+
+ const char* context = kInitContext;
if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
- for (const auto& [path_prefix, secontext] : paths_and_secontexts) {
- if (StartsWith(filename, path_prefix)) {
- context = secontext;
+ for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
+ if (StartsWith(filename, vendor_path_prefix)) {
+ context = kVendorContext;
}
}
}
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index 4322dc7..45d1852 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -537,13 +537,8 @@
filename_ = filename;
Subcontext* restart_action_subcontext = nullptr;
- if (subcontexts_) {
- for (auto& subcontext : *subcontexts_) {
- if (StartsWith(filename, subcontext.path_prefix())) {
- restart_action_subcontext = &subcontext;
- break;
- }
- }
+ if (subcontext_ && subcontext_->PathMatchesSubcontext(filename)) {
+ restart_action_subcontext = subcontext_;
}
std::vector<std::string> str_args(args.begin() + 2, args.end());
diff --git a/init/service_parser.h b/init/service_parser.h
index ace4d70..f063102 100644
--- a/init/service_parser.h
+++ b/init/service_parser.h
@@ -30,10 +30,10 @@
class ServiceParser : public SectionParser {
public:
ServiceParser(
- ServiceList* service_list, std::vector<Subcontext>* subcontexts,
+ ServiceList* service_list, Subcontext* subcontext,
const std::optional<InterfaceInheritanceHierarchyMap>& interface_inheritance_hierarchy)
: service_list_(service_list),
- subcontexts_(subcontexts),
+ subcontext_(subcontext),
interface_inheritance_hierarchy_(interface_inheritance_hierarchy),
service_(nullptr) {}
Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
@@ -84,7 +84,7 @@
bool IsValidName(const std::string& name) const;
ServiceList* service_list_;
- std::vector<Subcontext>* subcontexts_;
+ Subcontext* subcontext_;
std::optional<InterfaceInheritanceHierarchyMap> interface_inheritance_hierarchy_;
std::unique_ptr<Service> service_;
std::string filename_;
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index ec93b58..79fc372 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -49,15 +49,6 @@
namespace android {
namespace init {
-
-const std::string kInitContext = "u:r:init:s0";
-const std::string kVendorContext = "u:r:vendor_init:s0";
-
-const char* const paths_and_secontexts[2][2] = {
- {"/vendor", kVendorContext.c_str()},
- {"/odm", kVendorContext.c_str()},
-};
-
namespace {
class SubcontextProcess {
@@ -237,6 +228,15 @@
Fork();
}
+bool Subcontext::PathMatchesSubcontext(const std::string& path) {
+ for (const auto& prefix : path_prefixes_) {
+ if (StartsWith(path, prefix)) {
+ return true;
+ }
+ }
+ return false;
+}
+
Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
if (auto result = SendMessage(socket_, subcontext_command); !result) {
Restart();
@@ -313,13 +313,12 @@
static std::vector<Subcontext> subcontexts;
static bool shutting_down;
-std::vector<Subcontext>* InitializeSubcontexts() {
+std::unique_ptr<Subcontext> InitializeSubcontext() {
if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
- for (const auto& [path_prefix, secontext] : paths_and_secontexts) {
- subcontexts.emplace_back(path_prefix, secontext);
- }
+ return std::make_unique<Subcontext>(std::vector<std::string>{"/vendor", "/odm"},
+ kVendorContext);
}
- return &subcontexts;
+ return nullptr;
}
bool SubcontextChildReap(pid_t pid) {
diff --git a/init/subcontext.h b/init/subcontext.h
index 591521f..bcaad29 100644
--- a/init/subcontext.h
+++ b/init/subcontext.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _INIT_SUBCONTEXT_H
-#define _INIT_SUBCONTEXT_H
+#pragma once
#include <signal.h>
@@ -31,22 +30,21 @@
namespace android {
namespace init {
-extern const std::string kInitContext;
-extern const std::string kVendorContext;
-extern const char* const paths_and_secontexts[2][2];
+static constexpr const char kInitContext[] = "u:r:init:s0";
+static constexpr const char kVendorContext[] = "u:r:vendor_init:s0";
class Subcontext {
public:
- Subcontext(std::string path_prefix, std::string context)
- : path_prefix_(std::move(path_prefix)), context_(std::move(context)), pid_(0) {
+ Subcontext(std::vector<std::string> path_prefixes, std::string context)
+ : path_prefixes_(std::move(path_prefixes)), context_(std::move(context)), pid_(0) {
Fork();
}
Result<void> Execute(const std::vector<std::string>& args);
Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
void Restart();
+ bool PathMatchesSubcontext(const std::string& path);
- const std::string& path_prefix() const { return path_prefix_; }
const std::string& context() const { return context_; }
pid_t pid() const { return pid_; }
@@ -54,18 +52,16 @@
void Fork();
Result<SubcontextReply> TransmitMessage(const SubcontextCommand& subcontext_command);
- std::string path_prefix_;
+ std::vector<std::string> path_prefixes_;
std::string context_;
pid_t pid_;
android::base::unique_fd socket_;
};
int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map);
-std::vector<Subcontext>* InitializeSubcontexts();
+std::unique_ptr<Subcontext> InitializeSubcontext();
bool SubcontextChildReap(pid_t pid);
void SubcontextTerminate();
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/subcontext_benchmark.cpp b/init/subcontext_benchmark.cpp
index f6fee8a..ccef2f3 100644
--- a/init/subcontext_benchmark.cpp
+++ b/init/subcontext_benchmark.cpp
@@ -33,7 +33,7 @@
return;
}
- auto subcontext = Subcontext("path", context);
+ auto subcontext = Subcontext({"path"}, context);
free(context);
while (state.KeepRunning()) {
diff --git a/init/subcontext_test.cpp b/init/subcontext_test.cpp
index 7565eb6..9cac35e 100644
--- a/init/subcontext_test.cpp
+++ b/init/subcontext_test.cpp
@@ -52,7 +52,7 @@
auto context_string = std::string(context);
free(context);
- auto subcontext = Subcontext("dummy_path", context_string);
+ auto subcontext = Subcontext({"dummy_path"}, context_string);
ASSERT_NE(0, subcontext.pid());
test_function(subcontext, context_string);
diff --git a/libmeminfo/libmeminfo_test.cpp b/libmeminfo/libmeminfo_test.cpp
index 4c2be91..cf5341d 100644
--- a/libmeminfo/libmeminfo_test.cpp
+++ b/libmeminfo/libmeminfo_test.cpp
@@ -31,6 +31,7 @@
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
using namespace std;
using namespace android::meminfo;
@@ -334,7 +335,9 @@
// Check for names
EXPECT_EQ(vmas[0].name, "[anon:dalvik-zygote-jit-code-cache]");
EXPECT_EQ(vmas[1].name, "/system/framework/x86_64/boot-framework.art");
- EXPECT_EQ(vmas[2].name, "[anon:libc_malloc]");
+ EXPECT_TRUE(vmas[2].name == "[anon:libc_malloc]" ||
+ android::base::StartsWith(vmas[2].name, "[anon:scudo:"))
+ << "Unknown map name " << vmas[2].name;
EXPECT_EQ(vmas[3].name, "/system/priv-app/SettingsProvider/oat/x86_64/SettingsProvider.odex");
EXPECT_EQ(vmas[4].name, "/system/lib64/libhwui.so");
EXPECT_EQ(vmas[5].name, "[vsyscall]");
@@ -432,7 +435,9 @@
// Check for names
EXPECT_EQ(vmas[0].name, "[anon:dalvik-zygote-jit-code-cache]");
EXPECT_EQ(vmas[1].name, "/system/framework/x86_64/boot-framework.art");
- EXPECT_EQ(vmas[2].name, "[anon:libc_malloc]");
+ EXPECT_TRUE(vmas[2].name == "[anon:libc_malloc]" ||
+ android::base::StartsWith(vmas[2].name, "[anon:scudo:"))
+ << "Unknown map name " << vmas[2].name;
EXPECT_EQ(vmas[3].name, "/system/priv-app/SettingsProvider/oat/x86_64/SettingsProvider.odex");
EXPECT_EQ(vmas[4].name, "/system/lib64/libhwui.so");
EXPECT_EQ(vmas[5].name, "[vsyscall]");
diff --git a/libmemunreachable/MemUnreachable.cpp b/libmemunreachable/MemUnreachable.cpp
index ce937fd..c4add19 100644
--- a/libmemunreachable/MemUnreachable.cpp
+++ b/libmemunreachable/MemUnreachable.cpp
@@ -25,6 +25,7 @@
#include <unordered_map>
#include <android-base/macros.h>
+#include <android-base/strings.h>
#include <backtrace.h>
#include "Allocator.h"
@@ -250,7 +251,8 @@
} else if (mapping_name == current_lib) {
// .rodata or .data section
globals_mappings.emplace_back(*it);
- } else if (mapping_name == "[anon:libc_malloc]") {
+ } else if (mapping_name == "[anon:libc_malloc]" ||
+ android::base::StartsWith(mapping_name, "[anon:scudo:")) {
// named malloc mapping
heap_mappings.emplace_back(*it);
} else if (has_prefix(mapping_name, "[anon:dalvik-")) {
diff --git a/libmemunreachable/ScopedDisableMalloc.h b/libmemunreachable/ScopedDisableMalloc.h
index 655e826..dc863c9 100644
--- a/libmemunreachable/ScopedDisableMalloc.h
+++ b/libmemunreachable/ScopedDisableMalloc.h
@@ -34,8 +34,8 @@
void Disable() {
if (!disabled_) {
- malloc_disable();
disabled_ = true;
+ malloc_disable();
}
}
@@ -71,8 +71,7 @@
class ScopedDisableMallocTimeout {
public:
- explicit ScopedDisableMallocTimeout(
- std::chrono::milliseconds timeout = std::chrono::milliseconds(2000))
+ explicit ScopedDisableMallocTimeout(std::chrono::milliseconds timeout = std::chrono::seconds(10))
: timeout_(timeout), timed_out_(false), disable_malloc_() {
Disable();
}
diff --git a/libutils/Looper_test.cpp b/libutils/Looper_test.cpp
index 6fdc0ed..37bdf05 100644
--- a/libutils/Looper_test.cpp
+++ b/libutils/Looper_test.cpp
@@ -11,8 +11,9 @@
#include <utils/threads.h>
+// b/141212746 - increased for virtual platforms with higher volatility
// # of milliseconds to fudge stopwatch measurements
-#define TIMING_TOLERANCE_MS 25
+#define TIMING_TOLERANCE_MS 100
namespace android {