• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2019 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <memory>
18 #include <optional>
19 #include <string>
20 #include <unordered_set>
21 
22 #include <android-base/file.h>
23 #include <android/hardware/boot/1.1/IBootControl.h>
24 #include <gmock/gmock.h>
25 #include <gtest/gtest.h>
26 #include <libfiemap/image_manager.h>
27 #include <liblp/mock_property_fetcher.h>
28 #include <liblp/partition_opener.h>
29 #include <libsnapshot/snapshot.h>
30 #include <storage_literals/storage_literals.h>
31 #include <update_engine/update_metadata.pb.h>
32 
33 namespace android {
34 namespace snapshot {
35 
36 using android::fs_mgr::IPropertyFetcher;
37 using android::fs_mgr::MetadataBuilder;
38 using android::fs_mgr::testing::MockPropertyFetcher;
39 using android::hardware::boot::V1_1::MergeStatus;
40 using chromeos_update_engine::DeltaArchiveManifest;
41 using chromeos_update_engine::PartitionUpdate;
42 using testing::_;
43 using testing::AssertionResult;
44 using testing::NiceMock;
45 
46 using namespace android::storage_literals;
47 using namespace std::string_literals;
48 
49 // These are not reset between each test because it's expensive to create
50 // these resources (starting+connecting to gsid, zero-filling images).
51 extern std::unique_ptr<SnapshotManager> sm;
52 extern class TestDeviceInfo* test_device;
53 extern std::string fake_super;
54 static constexpr uint64_t kSuperSize = 32_MiB + 4_KiB;
55 static constexpr uint64_t kGroupSize = 32_MiB;
56 
57 // Redirect requests for "super" to our fake super partition.
58 class TestPartitionOpener final : public android::fs_mgr::PartitionOpener {
59   public:
TestPartitionOpener(const std::string & fake_super_path)60     explicit TestPartitionOpener(const std::string& fake_super_path)
61         : fake_super_path_(fake_super_path) {}
62 
63     android::base::unique_fd Open(const std::string& partition_name, int flags) const override;
64     bool GetInfo(const std::string& partition_name,
65                  android::fs_mgr::BlockDeviceInfo* info) const override;
66     std::string GetDeviceString(const std::string& partition_name) const override;
67 
68   private:
69     std::string fake_super_path_;
70 };
71 
72 class TestDeviceInfo : public SnapshotManager::IDeviceInfo {
73   public:
TestDeviceInfo()74     TestDeviceInfo() {}
TestDeviceInfo(const std::string & fake_super)75     explicit TestDeviceInfo(const std::string& fake_super) { set_fake_super(fake_super); }
TestDeviceInfo(const std::string & fake_super,const std::string & slot_suffix)76     TestDeviceInfo(const std::string& fake_super, const std::string& slot_suffix)
77         : TestDeviceInfo(fake_super) {
78         set_slot_suffix(slot_suffix);
79     }
GetMetadataDir()80     std::string GetMetadataDir() const override { return "/metadata/ota/test"s; }
GetSlotSuffix()81     std::string GetSlotSuffix() const override { return slot_suffix_; }
GetOtherSlotSuffix()82     std::string GetOtherSlotSuffix() const override { return slot_suffix_ == "_a" ? "_b" : "_a"; }
GetSuperDevice(uint32_t slot)83     std::string GetSuperDevice([[maybe_unused]] uint32_t slot) const override { return "super"; }
GetPartitionOpener()84     const android::fs_mgr::IPartitionOpener& GetPartitionOpener() const override {
85         return *opener_.get();
86     }
SetBootControlMergeStatus(MergeStatus status)87     bool SetBootControlMergeStatus(MergeStatus status) override {
88         merge_status_ = status;
89         return true;
90     }
IsOverlayfsSetup()91     bool IsOverlayfsSetup() const override { return false; }
IsRecovery()92     bool IsRecovery() const override { return recovery_; }
SetSlotAsUnbootable(unsigned int slot)93     bool SetSlotAsUnbootable(unsigned int slot) override {
94         unbootable_slots_.insert(slot);
95         return true;
96     }
IsTestDevice()97     bool IsTestDevice() const override { return true; }
IsFirstStageInit()98     bool IsFirstStageInit() const override { return first_stage_init_; }
OpenImageManager()99     std::unique_ptr<IImageManager> OpenImageManager() const override {
100         return IDeviceInfo::OpenImageManager("ota/test");
101     }
102 
IsSlotUnbootable(uint32_t slot)103     bool IsSlotUnbootable(uint32_t slot) { return unbootable_slots_.count(slot) != 0; }
104 
set_slot_suffix(const std::string & suffix)105     void set_slot_suffix(const std::string& suffix) { slot_suffix_ = suffix; }
set_fake_super(const std::string & path)106     void set_fake_super(const std::string& path) {
107         opener_ = std::make_unique<TestPartitionOpener>(path);
108     }
set_recovery(bool value)109     void set_recovery(bool value) { recovery_ = value; }
set_first_stage_init(bool value)110     void set_first_stage_init(bool value) { first_stage_init_ = value; }
merge_status()111     MergeStatus merge_status() const { return merge_status_; }
112 
113   private:
114     std::string slot_suffix_ = "_a";
115     std::unique_ptr<TestPartitionOpener> opener_;
116     MergeStatus merge_status_;
117     bool recovery_ = false;
118     bool first_stage_init_ = false;
119     std::unordered_set<uint32_t> unbootable_slots_;
120 };
121 
122 class SnapshotTestPropertyFetcher : public android::fs_mgr::testing::MockPropertyFetcher {
123   public:
SnapshotTestPropertyFetcher(const std::string & slot_suffix)124     SnapshotTestPropertyFetcher(const std::string& slot_suffix) {
125         using testing::Return;
126         ON_CALL(*this, GetProperty("ro.boot.slot_suffix", _)).WillByDefault(Return(slot_suffix));
127         ON_CALL(*this, GetBoolProperty("ro.boot.dynamic_partitions", _))
128                 .WillByDefault(Return(true));
129         ON_CALL(*this, GetBoolProperty("ro.boot.dynamic_partitions_retrofit", _))
130                 .WillByDefault(Return(false));
131         ON_CALL(*this, GetBoolProperty("ro.virtual_ab.enabled", _)).WillByDefault(Return(true));
132     }
133 
134     static void SetUp(const std::string& slot_suffix = "_a") { Reset(slot_suffix); }
135 
TearDown()136     static void TearDown() { Reset("_a"); }
137 
138   private:
Reset(const std::string & slot_suffix)139     static void Reset(const std::string& slot_suffix) {
140         IPropertyFetcher::OverrideForTesting(
141                 std::make_unique<NiceMock<SnapshotTestPropertyFetcher>>(slot_suffix));
142     }
143 };
144 
145 // Helper for error-spam-free cleanup.
146 void DeleteBackingImage(android::fiemap::IImageManager* manager, const std::string& name);
147 
148 // Write some random data to the given device.
149 // If expect_size is not specified, will write until reaching end of the device.
150 // Expect space of |path| is multiple of 4K.
151 bool WriteRandomData(const std::string& path, std::optional<size_t> expect_size = std::nullopt,
152                      std::string* hash = nullptr);
153 bool WriteRandomData(ICowWriter* writer, std::string* hash = nullptr);
154 std::string HashSnapshot(ISnapshotWriter* writer);
155 
156 std::optional<std::string> GetHash(const std::string& path);
157 
158 // Add partitions and groups described by |manifest|.
159 AssertionResult FillFakeMetadata(MetadataBuilder* builder, const DeltaArchiveManifest& manifest,
160                                  const std::string& suffix);
161 
162 // In the update package metadata, set a partition with the given size.
163 void SetSize(PartitionUpdate* partition_update, uint64_t size);
164 
165 // Get partition size from update package metadata.
166 uint64_t GetSize(PartitionUpdate* partition_update);
167 
168 // Util class for test cases on low space scenario. These tests assumes image manager
169 // uses /data as backup device.
170 class LowSpaceUserdata {
171   public:
172     // Set the maximum free space allowed for this test. If /userdata has more space than the given
173     // number, a file is allocated to consume space.
174     AssertionResult Init(uint64_t max_free_space);
175 
176     uint64_t free_space() const;
177     uint64_t available_space() const;
178     uint64_t bsize() const;
179 
180   private:
181     AssertionResult ReadUserdataStats();
182 
183     static constexpr const char* kUserDataDevice = "/data";
184     std::unique_ptr<TemporaryFile> big_file_;
185     bool initialized_ = false;
186     uint64_t free_space_ = 0;
187     uint64_t available_space_ = 0;
188     uint64_t bsize_ = 0;
189 };
190 
191 bool IsVirtualAbEnabled();
192 
193 #define SKIP_IF_NON_VIRTUAL_AB()                                                        \
194     do {                                                                                \
195         if (!IsVirtualAbEnabled()) GTEST_SKIP() << "Test for Virtual A/B devices only"; \
196     } while (0)
197 
198 #define RETURN_IF_NON_VIRTUAL_AB_MSG(msg) \
199     do {                                  \
200         if (!IsVirtualAbEnabled()) {      \
201             std::cerr << (msg);           \
202             return;                       \
203         }                                 \
204     } while (0)
205 
206 #define RETURN_IF_NON_VIRTUAL_AB() RETURN_IF_NON_VIRTUAL_AB_MSG("")
207 
208 }  // namespace snapshot
209 }  // namespace android
210