1 //
2 // Copyright (C) 2018 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "update_engine/aosp/dynamic_partition_control_android.h"
18 
19 #include <algorithm>
20 #include <chrono>  // NOLINT(build/c++11) - using libsnapshot / liblp API
21 #include <cstdint>
22 #include <map>
23 #include <memory>
24 #include <set>
25 #include <string>
26 #include <string_view>
27 #include <utility>
28 #include <vector>
29 
30 #include <android-base/properties.h>
31 #include <android-base/strings.h>
32 #include <base/files/file_util.h>
33 #include <base/logging.h>
34 #include <base/strings/string_util.h>
35 #include <base/strings/stringprintf.h>
36 #include <bootloader_message/bootloader_message.h>
37 #include <fs_mgr.h>
38 #include <fs_mgr_dm_linear.h>
39 #include <fs_mgr_overlayfs.h>
40 #include <libavb/libavb.h>
41 #include <libdm/dm.h>
42 #include <liblp/liblp.h>
43 #include <libsnapshot/cow_writer.h>
44 #include <libsnapshot/snapshot.h>
45 #include <libsnapshot/snapshot_stub.h>
46 
47 #include "update_engine/aosp/cleanup_previous_update_action.h"
48 #include "update_engine/aosp/dynamic_partition_utils.h"
49 #include "update_engine/common/boot_control_interface.h"
50 #include "update_engine/common/dynamic_partition_control_interface.h"
51 #include "update_engine/common/error_code.h"
52 #include "update_engine/common/platform_constants.h"
53 #include "update_engine/common/utils.h"
54 #include "update_engine/payload_consumer/cow_writer_file_descriptor.h"
55 #include "update_engine/payload_consumer/delta_performer.h"
56 
57 using android::base::GetBoolProperty;
58 using android::base::GetProperty;
59 using android::base::Join;
60 using android::dm::DeviceMapper;
61 using android::dm::DmDeviceState;
62 using android::fs_mgr::CreateLogicalPartition;
63 using android::fs_mgr::CreateLogicalPartitionParams;
64 using android::fs_mgr::DestroyLogicalPartition;
65 using android::fs_mgr::Fstab;
66 using android::fs_mgr::MetadataBuilder;
67 using android::fs_mgr::Partition;
68 using android::fs_mgr::PartitionOpener;
69 using android::fs_mgr::SlotSuffixForSlotNumber;
70 using android::snapshot::OptimizeSourceCopyOperation;
71 using android::snapshot::Return;
72 using android::snapshot::SnapshotManager;
73 using android::snapshot::SnapshotManagerStub;
74 using android::snapshot::UpdateState;
75 using base::StringPrintf;
76 
77 namespace chromeos_update_engine {
78 
79 constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
80 constexpr char kRetrfoitDynamicPartitions[] =
81     "ro.boot.dynamic_partitions_retrofit";
82 constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
83 constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
84 constexpr char kVirtualAbCompressionEnabled[] =
85     "ro.virtual_ab.compression.enabled";
86 constexpr auto&& kVirtualAbCompressionXorEnabled =
87     "ro.virtual_ab.compression.xor.enabled";
88 constexpr char kVirtualAbUserspaceSnapshotsEnabled[] =
89     "ro.virtual_ab.userspace.snapshots.enabled";
90 
91 // Currently, android doesn't have a retrofit prop for VAB Compression. However,
92 // struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
93 // is here just to simplify code. Replace it with real retrofit prop name once
94 // there is one.
95 constexpr char kVirtualAbCompressionRetrofit[] = "";
96 constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
97 // Map timeout for dynamic partitions.
98 constexpr std::chrono::milliseconds kMapTimeout{1000};
99 // Map timeout for dynamic partitions with snapshots. Since several devices
100 // needs to be mapped, this timeout is longer than |kMapTimeout|.
101 constexpr std::chrono::milliseconds kMapSnapshotTimeout{10000};
102 
~DynamicPartitionControlAndroid()103 DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
104   UnmapAllPartitions();
105   metadata_device_.reset();
106 }
107 
GetFeatureFlag(const char * enable_prop,const char * retrofit_prop)108 static FeatureFlag GetFeatureFlag(const char* enable_prop,
109                                   const char* retrofit_prop) {
110   // Default retrofit to false if retrofit_prop is empty.
111   bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
112                   GetBoolProperty(retrofit_prop, false);
113   bool enabled = GetBoolProperty(enable_prop, false);
114   if (retrofit && !enabled) {
115     LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
116                << " is not. These sysprops are inconsistent. Assume that "
117                << enable_prop << " is true from now on.";
118   }
119   if (retrofit) {
120     return FeatureFlag(FeatureFlag::Value::RETROFIT);
121   }
122   if (enabled) {
123     return FeatureFlag(FeatureFlag::Value::LAUNCH);
124   }
125   return FeatureFlag(FeatureFlag::Value::NONE);
126 }
127 
DynamicPartitionControlAndroid(uint32_t source_slot)128 DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
129     uint32_t source_slot)
130     : dynamic_partitions_(
131           GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
132       virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
133       virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
134                                              kVirtualAbCompressionRetrofit)),
135       virtual_ab_compression_xor_(
136           GetFeatureFlag(kVirtualAbCompressionXorEnabled, "")),
137       virtual_ab_userspace_snapshots_(
138           GetFeatureFlag(kVirtualAbUserspaceSnapshotsEnabled, nullptr)),
139       source_slot_(source_slot) {
140   if (GetVirtualAbFeatureFlag().IsEnabled()) {
141     snapshot_ = SnapshotManager::New();
142   } else {
143     snapshot_ = SnapshotManagerStub::New();
144   }
145   CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
146 }
147 
GetDynamicPartitionsFeatureFlag()148 FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
149   return dynamic_partitions_;
150 }
151 
GetVirtualAbFeatureFlag()152 FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
153   return virtual_ab_;
154 }
155 
156 FeatureFlag
GetVirtualAbCompressionFeatureFlag()157 DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
158   if constexpr (constants::kIsRecovery) {
159     // Don't attempt VABC in recovery
160     return FeatureFlag(FeatureFlag::Value::NONE);
161   }
162   return virtual_ab_compression_;
163 }
164 
165 FeatureFlag
GetVirtualAbCompressionXorFeatureFlag()166 DynamicPartitionControlAndroid::GetVirtualAbCompressionXorFeatureFlag() {
167   return virtual_ab_compression_xor_;
168 }
169 
OptimizeOperation(const std::string & partition_name,const InstallOperation & operation,InstallOperation * optimized)170 bool DynamicPartitionControlAndroid::OptimizeOperation(
171     const std::string& partition_name,
172     const InstallOperation& operation,
173     InstallOperation* optimized) {
174   switch (operation.type()) {
175     case InstallOperation::SOURCE_COPY:
176       return target_supports_snapshot_ &&
177              GetVirtualAbFeatureFlag().IsEnabled() &&
178              mapped_devices_.count(partition_name +
179                                    SlotSuffixForSlotNumber(target_slot_)) > 0 &&
180              OptimizeSourceCopyOperation(operation, optimized);
181       break;
182     default:
183       break;
184   }
185   return false;
186 }
187 
MapPartitionInternal(const std::string & super_device,const std::string & target_partition_name,uint32_t slot,bool force_writable,std::string * path)188 bool DynamicPartitionControlAndroid::MapPartitionInternal(
189     const std::string& super_device,
190     const std::string& target_partition_name,
191     uint32_t slot,
192     bool force_writable,
193     std::string* path) {
194   CreateLogicalPartitionParams params = {
195       .block_device = super_device,
196       .metadata_slot = slot,
197       .partition_name = target_partition_name,
198       .force_writable = force_writable,
199   };
200   bool success = false;
201   if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
202       force_writable && ExpectMetadataMounted()) {
203     // Only target partitions are mapped with force_writable. On Virtual
204     // A/B devices, target partitions may overlap with source partitions, so
205     // they must be mapped with snapshot.
206     // One exception is when /metadata is not mounted. Fallback to
207     // CreateLogicalPartition as snapshots are not created in the first place.
208     params.timeout_ms = kMapSnapshotTimeout;
209     success = snapshot_->MapUpdateSnapshot(params, path);
210   } else {
211     params.timeout_ms = kMapTimeout;
212     success = CreateLogicalPartition(params, path);
213   }
214 
215   if (!success) {
216     LOG(ERROR) << "Cannot map " << target_partition_name << " in "
217                << super_device << " on device mapper.";
218     return false;
219   }
220   LOG(INFO) << "Succesfully mapped " << target_partition_name
221             << " to device mapper (force_writable = " << force_writable
222             << "); device path at " << *path;
223   mapped_devices_.insert(target_partition_name);
224   return true;
225 }
226 
MapPartitionOnDeviceMapper(const std::string & super_device,const std::string & target_partition_name,uint32_t slot,bool force_writable,std::string * path)227 bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
228     const std::string& super_device,
229     const std::string& target_partition_name,
230     uint32_t slot,
231     bool force_writable,
232     std::string* path) {
233   DmDeviceState state = GetState(target_partition_name);
234   if (state == DmDeviceState::ACTIVE) {
235     if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
236       if (GetDmDevicePathByName(target_partition_name, path)) {
237         LOG(INFO) << target_partition_name
238                   << " is mapped on device mapper: " << *path;
239         return true;
240       }
241       LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
242       return false;
243     }
244     // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
245     // the device might be mapped incorrectly before. Attempt to unmap it.
246     // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
247     // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
248     // should directly call GetDmDevicePathByName.
249     if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
250       LOG(ERROR) << target_partition_name
251                  << " is mapped before the update, and it cannot be unmapped.";
252       return false;
253     }
254     state = GetState(target_partition_name);
255     if (state != DmDeviceState::INVALID) {
256       LOG(ERROR) << target_partition_name << " is unmapped but state is "
257                  << static_cast<std::underlying_type_t<DmDeviceState>>(state);
258       return false;
259     }
260   }
261   if (state == DmDeviceState::INVALID) {
262     return MapPartitionInternal(
263         super_device, target_partition_name, slot, force_writable, path);
264   }
265 
266   LOG(ERROR) << target_partition_name
267              << " is mapped on device mapper but state is unknown: "
268              << static_cast<std::underlying_type_t<DmDeviceState>>(state);
269   return false;
270 }
271 
UnmapPartitionOnDeviceMapper(const std::string & target_partition_name)272 bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
273     const std::string& target_partition_name) {
274   if (DeviceMapper::Instance().GetState(target_partition_name) !=
275       DmDeviceState::INVALID) {
276     // Partitions at target slot on non-Virtual A/B devices are mapped as
277     // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
278     // preopt apps as dm-linear.
279     // Call DestroyLogicalPartition to handle these cases.
280     bool success = DestroyLogicalPartition(target_partition_name);
281 
282     // On a Virtual A/B device, |target_partition_name| may be a leftover from
283     // a paused update. Clean up any underlying devices.
284     if (ExpectMetadataMounted()) {
285       success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
286     } else {
287       LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
288                 << ") because metadata is not mounted";
289     }
290 
291     if (!success) {
292       LOG(ERROR) << "Cannot unmap " << target_partition_name
293                  << " from device mapper.";
294       return false;
295     }
296     LOG(INFO) << "Successfully unmapped " << target_partition_name
297               << " from device mapper.";
298   }
299   mapped_devices_.erase(target_partition_name);
300   return true;
301 }
302 
UnmapAllPartitions()303 bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
304   snapshot_->UnmapAllSnapshots();
305   if (mapped_devices_.empty()) {
306     return false;
307   }
308   // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
309   // a copy is needed for the loop.
310   std::set<std::string> mapped = mapped_devices_;
311   LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
312   for (const auto& partition_name : mapped) {
313     ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
314   }
315   return true;
316 }
317 
Cleanup()318 void DynamicPartitionControlAndroid::Cleanup() {
319   UnmapAllPartitions();
320   metadata_device_.reset();
321   if (GetVirtualAbFeatureFlag().IsEnabled()) {
322     snapshot_ = SnapshotManager::New();
323   } else {
324     snapshot_ = SnapshotManagerStub::New();
325   }
326   CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
327 }
328 
DeviceExists(const std::string & path)329 bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
330   return base::PathExists(base::FilePath(path));
331 }
332 
GetState(const std::string & name)333 android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
334     const std::string& name) {
335   return DeviceMapper::Instance().GetState(name);
336 }
337 
GetDmDevicePathByName(const std::string & name,std::string * path)338 bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
339     const std::string& name, std::string* path) {
340   return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
341 }
342 
343 std::unique_ptr<MetadataBuilder>
LoadMetadataBuilder(const std::string & super_device,uint32_t slot)344 DynamicPartitionControlAndroid::LoadMetadataBuilder(
345     const std::string& super_device, uint32_t slot) {
346   auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
347   if (builder == nullptr) {
348     LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
349                  << " in " << super_device;
350     return nullptr;
351   }
352   LOG(INFO) << "Loaded metadata from slot "
353             << BootControlInterface::SlotName(slot) << " in " << super_device;
354   return builder;
355 }
356 
357 std::unique_ptr<MetadataBuilder>
LoadMetadataBuilder(const std::string & super_device,uint32_t source_slot,uint32_t target_slot)358 DynamicPartitionControlAndroid::LoadMetadataBuilder(
359     const std::string& super_device,
360     uint32_t source_slot,
361     uint32_t target_slot) {
362   bool always_keep_source_slot = !target_supports_snapshot_;
363   auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
364                                                super_device,
365                                                source_slot,
366                                                target_slot,
367                                                always_keep_source_slot);
368   if (builder == nullptr) {
369     LOG(WARNING) << "No metadata slot "
370                  << BootControlInterface::SlotName(source_slot) << " in "
371                  << super_device;
372     return nullptr;
373   }
374   LOG(INFO) << "Created metadata for new update from slot "
375             << BootControlInterface::SlotName(source_slot) << " in "
376             << super_device;
377   return builder;
378 }
379 
StoreMetadata(const std::string & super_device,MetadataBuilder * builder,uint32_t target_slot)380 bool DynamicPartitionControlAndroid::StoreMetadata(
381     const std::string& super_device,
382     MetadataBuilder* builder,
383     uint32_t target_slot) {
384   auto metadata = builder->Export();
385   if (metadata == nullptr) {
386     LOG(ERROR) << "Cannot export metadata to slot "
387                << BootControlInterface::SlotName(target_slot) << " in "
388                << super_device;
389     return false;
390   }
391 
392   if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
393     if (!FlashPartitionTable(super_device, *metadata)) {
394       LOG(ERROR) << "Cannot write metadata to " << super_device;
395       return false;
396     }
397     LOG(INFO) << "Written metadata to " << super_device;
398   } else {
399     if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
400       LOG(ERROR) << "Cannot write metadata to slot "
401                  << BootControlInterface::SlotName(target_slot) << " in "
402                  << super_device;
403       return false;
404     }
405     LOG(INFO) << "Copied metadata to slot "
406               << BootControlInterface::SlotName(target_slot) << " in "
407               << super_device;
408   }
409 
410   return true;
411 }
412 
GetDeviceDir(std::string * out)413 bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
414   // We can't use fs_mgr to look up |partition_name| because fstab
415   // doesn't list every slot partition (it uses the slotselect option
416   // to mask the suffix).
417   //
418   // We can however assume that there's an entry for the /misc mount
419   // point and use that to get the device file for the misc
420   // partition. This helps us locate the disk that |partition_name|
421   // resides on. From there we'll assume that a by-name scheme is used
422   // so we can just replace the trailing "misc" by the given
423   // |partition_name| and suffix corresponding to |slot|, e.g.
424   //
425   //   /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
426   //   /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
427   //
428   // If needed, it's possible to relax the by-name assumption in the
429   // future by trawling /sys/block looking for the appropriate sibling
430   // of misc and then finding an entry in /dev matching the sysfs
431   // entry.
432 
433   std::string err, misc_device = get_bootloader_message_blk_device(&err);
434   if (misc_device.empty()) {
435     LOG(ERROR) << "Unable to get misc block device: " << err;
436     return false;
437   }
438 
439   if (!utils::IsSymlink(misc_device.c_str())) {
440     LOG(ERROR) << "Device file " << misc_device << " for /misc "
441                << "is not a symlink.";
442     return false;
443   }
444   *out = base::FilePath(misc_device).DirName().value();
445   return true;
446 }
447 
PreparePartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,bool update,uint64_t * required_size,ErrorCode * error)448 bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
449     uint32_t source_slot,
450     uint32_t target_slot,
451     const DeltaArchiveManifest& manifest,
452     bool update,
453     uint64_t* required_size,
454     ErrorCode* error) {
455   source_slot_ = source_slot;
456   target_slot_ = target_slot;
457   if (required_size != nullptr) {
458     *required_size = 0;
459   }
460 
461   if (fs_mgr_overlayfs_is_setup()) {
462     // Non DAP devices can use overlayfs as well.
463     LOG(ERROR)
464         << "overlayfs overrides are active and can interfere with our "
465            "resources.\n"
466         << "run adb enable-verity to deactivate if required and try again.";
467     if (error) {
468       *error = ErrorCode::kOverlayfsenabledError;
469       return false;
470     }
471   }
472 
473   // If metadata is erased but not formatted, it is possible to not mount
474   // it in recovery. It is acceptable to skip mounting and choose fallback path
475   // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
476   TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
477 
478   if (update) {
479     TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
480   }
481 
482   if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
483     return true;
484   }
485 
486   if (target_slot == source_slot) {
487     LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
488     return false;
489   }
490 
491   if (!SetTargetBuildVars(manifest)) {
492     return false;
493   }
494   for (auto& list : dynamic_partition_list_) {
495     list.clear();
496   }
497 
498   // Although the current build supports dynamic partitions, the given payload
499   // doesn't use it for target partitions. This could happen when applying a
500   // retrofit update. Skip updating the partition metadata for the target slot.
501   if (!is_target_dynamic_) {
502     return true;
503   }
504 
505   if (!update)
506     return true;
507 
508   bool delete_source = false;
509 
510   if (GetVirtualAbFeatureFlag().IsEnabled()) {
511     // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
512     // called before calling UnmapUpdateSnapshot.
513     // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
514     //   calls BeginUpdate() which resets update state
515     // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
516     //   failed in recovery, explicitly CancelUpdate().
517     if (target_supports_snapshot_) {
518       if (PrepareSnapshotPartitionsForUpdate(
519               source_slot, target_slot, manifest, required_size)) {
520         return true;
521       }
522 
523       // Virtual A/B device doing Virtual A/B update in Android mode must use
524       // snapshots.
525       if (!IsRecovery()) {
526         LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
527                    << "mode";
528         return false;
529       }
530 
531       delete_source = true;
532       LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
533                 << "Attempt to overwrite existing partitions if possible";
534     } else {
535       // Downgrading to an non-Virtual A/B build or is secondary OTA.
536       LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
537                 << "snapshots.";
538     }
539 
540     // In recovery, if /metadata is not mounted, it is likely that metadata
541     // partition is erased and not formatted yet. After sideloading, when
542     // rebooting into the new version, init will erase metadata partition,
543     // hence the failure of CancelUpdate() can be ignored here.
544     // However, if metadata is mounted and CancelUpdate fails, sideloading
545     // should not proceed because during next boot, snapshots will overlay on
546     // the devices incorrectly.
547     if (ExpectMetadataMounted()) {
548       TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
549     } else {
550       LOG(INFO) << "Skip canceling previous update because metadata is not "
551                 << "mounted";
552     }
553   }
554 
555   // TODO(xunchang) support partial update on non VAB enabled devices.
556   TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
557       source_slot, target_slot, manifest, delete_source));
558 
559   if (required_size != nullptr) {
560     *required_size = 0;
561   }
562   return true;
563 }
564 
SetTargetBuildVars(const DeltaArchiveManifest & manifest)565 bool DynamicPartitionControlAndroid::SetTargetBuildVars(
566     const DeltaArchiveManifest& manifest) {
567   // Precondition: current build supports dynamic partition.
568   CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
569 
570   bool is_target_dynamic =
571       !manifest.dynamic_partition_metadata().groups().empty();
572   bool target_supports_snapshot =
573       manifest.dynamic_partition_metadata().snapshot_enabled();
574 
575   if (manifest.partial_update()) {
576     // Partial updates requires DAP. On partial updates that does not involve
577     // dynamic partitions, groups() can be empty, so also assume
578     // is_target_dynamic in this case. This assumption should be safe because we
579     // also check target_supports_snapshot below, which presumably also implies
580     // target build supports dynamic partition.
581     if (!is_target_dynamic) {
582       LOG(INFO) << "Assuming target build supports dynamic partitions for "
583                    "partial updates.";
584       is_target_dynamic = true;
585     }
586 
587     // Partial updates requires Virtual A/B. Double check that both current
588     // build and target build supports Virtual A/B.
589     if (!GetVirtualAbFeatureFlag().IsEnabled()) {
590       LOG(ERROR) << "Partial update cannot be applied on a device that does "
591                     "not support snapshots.";
592       return false;
593     }
594     if (!target_supports_snapshot) {
595       LOG(ERROR) << "Cannot apply partial update to a build that does not "
596                     "support snapshots.";
597       return false;
598     }
599   }
600 
601   // Store the flags.
602   is_target_dynamic_ = is_target_dynamic;
603   // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
604   // snapshots would not work without dynamic partition.
605   if (is_target_dynamic_) {
606     target_supports_snapshot_ = target_supports_snapshot;
607   }
608   return true;
609 }
610 
611 namespace {
612 // Try our best to erase AVB footer.
613 class AvbFooterEraser {
614  public:
AvbFooterEraser(const std::string & path)615   explicit AvbFooterEraser(const std::string& path) : path_(path) {}
Erase()616   bool Erase() {
617     // Try to mark the block device read-only. Ignore any
618     // failure since this won't work when passing regular files.
619     ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
620 
621     fd_.reset(new EintrSafeFileDescriptor());
622     int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
623     TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
624 
625     // Need to write end-AVB_FOOTER_SIZE to end.
626     static_assert(AVB_FOOTER_SIZE > 0);
627     off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
628     TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
629     uint64_t write_size = AVB_FOOTER_SIZE;
630     LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
631               << (offset + write_size) << "] (" << write_size << " bytes)";
632     brillo::Blob zeros(write_size);
633     TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
634     return true;
635   }
~AvbFooterEraser()636   ~AvbFooterEraser() {
637     TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
638     if (!fd_->Close()) {
639       LOG(WARNING) << "Failed to close fd for " << path_;
640     }
641   }
642 
643  private:
644   std::string path_;
645   FileDescriptorPtr fd_;
646 };
647 
648 }  // namespace
649 
650 std::optional<bool>
IsAvbEnabledOnSystemOther()651 DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
652   auto prefix = GetProperty(kPostinstallFstabPrefix, "");
653   if (prefix.empty()) {
654     LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
655     return std::nullopt;
656   }
657   auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
658   return IsAvbEnabledInFstab(path);
659 }
660 
IsAvbEnabledInFstab(const std::string & path)661 std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
662     const std::string& path) {
663   Fstab fstab;
664   if (!ReadFstabFromFile(path, &fstab)) {
665     PLOG(WARNING) << "Cannot read fstab from " << path;
666     if (errno == ENOENT) {
667       return false;
668     }
669     return std::nullopt;
670   }
671   for (const auto& entry : fstab) {
672     if (!entry.avb_keys.empty()) {
673       return true;
674     }
675   }
676   return false;
677 }
678 
GetSystemOtherPath(uint32_t source_slot,uint32_t target_slot,const std::string & partition_name_suffix,std::string * path,bool * should_unmap)679 bool DynamicPartitionControlAndroid::GetSystemOtherPath(
680     uint32_t source_slot,
681     uint32_t target_slot,
682     const std::string& partition_name_suffix,
683     std::string* path,
684     bool* should_unmap) {
685   path->clear();
686   *should_unmap = false;
687 
688   // Check that AVB is enabled on system_other before erasing.
689   auto has_avb = IsAvbEnabledOnSystemOther();
690   TEST_AND_RETURN_FALSE(has_avb.has_value());
691   if (!has_avb.value()) {
692     LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
693     return true;
694   }
695 
696   if (!IsRecovery()) {
697     // Found unexpected avb_keys for system_other on devices retrofitting
698     // dynamic partitions. Previous crash in update_engine may leave logical
699     // partitions mapped on physical system_other partition. It is difficult to
700     // handle these cases. Just fail.
701     if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
702       LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
703                  << "retrofit dynamic partitions. They should not have AVB "
704                  << "enabled on system_other.";
705       return false;
706     }
707   }
708 
709   std::string device_dir_str;
710   TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
711   base::FilePath device_dir(device_dir_str);
712 
713   // On devices without dynamic partition, search for static partitions.
714   if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
715     *path = device_dir.Append(partition_name_suffix).value();
716     TEST_AND_RETURN_FALSE(DeviceExists(*path));
717     return true;
718   }
719 
720   auto source_super_device =
721       device_dir.Append(GetSuperPartitionName(source_slot)).value();
722 
723   auto builder = LoadMetadataBuilder(source_super_device, source_slot);
724   if (builder == nullptr) {
725     if (IsRecovery()) {
726       // It might be corrupted for some reason. It should still be able to
727       // sideload.
728       LOG(WARNING) << "Super partition metadata cannot be read from the source "
729                    << "slot, skip erasing.";
730       return true;
731     } else {
732       // Device has booted into Android mode, indicating that the super
733       // partition metadata should be there.
734       LOG(ERROR) << "Super partition metadata cannot be read from the source "
735                  << "slot. This is unexpected on devices with dynamic "
736                  << "partitions enabled.";
737       return false;
738     }
739   }
740   auto p = builder->FindPartition(partition_name_suffix);
741   if (p == nullptr) {
742     // If the source slot is flashed without system_other, it does not exist
743     // in super partition metadata at source slot. It is safe to skip it.
744     LOG(INFO) << "Can't find " << partition_name_suffix
745               << " in metadata source slot, skip erasing.";
746     return true;
747   }
748   // System_other created by flashing tools should be erased.
749   // If partition is created by update_engine (via NewForUpdate), it is a
750   // left-over partition from the previous update and does not contain
751   // system_other, hence there is no need to erase.
752   // Note the reverse is not necessary true. If the flag is not set, we don't
753   // know if the partition is created by update_engine or by flashing tools
754   // because older versions of super partition metadata does not contain this
755   // flag. It is okay to erase the AVB footer anyways.
756   if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
757     LOG(INFO) << partition_name_suffix
758               << " does not contain system_other, skip erasing.";
759     return true;
760   }
761 
762   if (p->size() < AVB_FOOTER_SIZE) {
763     LOG(INFO) << partition_name_suffix << " has length " << p->size()
764               << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
765               << "), skip erasing.";
766     return true;
767   }
768 
769   // Delete any pre-existing device with name |partition_name_suffix| and
770   // also remove it from |mapped_devices_|.
771   // In recovery, metadata might not be mounted, and
772   // UnmapPartitionOnDeviceMapper might fail. However,
773   // it is unusual that system_other has already been mapped. Hence, just skip.
774   TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
775   // Use CreateLogicalPartition directly to avoid mapping with existing
776   // snapshots.
777   CreateLogicalPartitionParams params = {
778       .block_device = source_super_device,
779       .metadata_slot = source_slot,
780       .partition_name = partition_name_suffix,
781       .force_writable = true,
782       .timeout_ms = kMapTimeout,
783   };
784   TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
785   *should_unmap = true;
786   return true;
787 }
788 
EraseSystemOtherAvbFooter(uint32_t source_slot,uint32_t target_slot)789 bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
790     uint32_t source_slot, uint32_t target_slot) {
791   LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
792 
793   const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
794   const std::string partition_name_suffix = "system" + target_suffix;
795 
796   std::string path;
797   bool should_unmap = false;
798 
799   TEST_AND_RETURN_FALSE(GetSystemOtherPath(
800       source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
801 
802   if (path.empty()) {
803     return true;
804   }
805 
806   bool ret = AvbFooterEraser(path).Erase();
807 
808   // Delete |partition_name_suffix| from device mapper and from
809   // |mapped_devices_| again so that it does not interfere with update process.
810   // In recovery, metadata might not be mounted, and
811   // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
812   // should be called. If DestroyLogicalPartition does fail, it is still okay
813   // to skip the error here and let Prepare*() fail later.
814   if (should_unmap) {
815     TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
816   }
817 
818   return ret;
819 }
820 
PrepareDynamicPartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,bool delete_source)821 bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
822     uint32_t source_slot,
823     uint32_t target_slot,
824     const DeltaArchiveManifest& manifest,
825     bool delete_source) {
826   const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
827 
828   // Unmap all the target dynamic partitions because they would become
829   // inconsistent with the new metadata.
830   for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
831     for (const auto& partition_name : group.partition_names()) {
832       if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
833         return false;
834       }
835     }
836   }
837 
838   std::string device_dir_str;
839   TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
840   base::FilePath device_dir(device_dir_str);
841   auto source_device =
842       device_dir.Append(GetSuperPartitionName(source_slot)).value();
843 
844   auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
845   if (builder == nullptr) {
846     LOG(ERROR) << "No metadata at "
847                << BootControlInterface::SlotName(source_slot);
848     return false;
849   }
850 
851   if (delete_source) {
852     TEST_AND_RETURN_FALSE(
853         DeleteSourcePartitions(builder.get(), source_slot, manifest));
854   }
855 
856   TEST_AND_RETURN_FALSE(
857       UpdatePartitionMetadata(builder.get(), target_slot, manifest));
858 
859   auto target_device =
860       device_dir.Append(GetSuperPartitionName(target_slot)).value();
861 
862   return StoreMetadata(target_device, builder.get(), target_slot);
863 }
864 
865 DynamicPartitionControlAndroid::SpaceLimit
GetSpaceLimit(bool use_snapshot)866 DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
867   // On device retrofitting dynamic partitions, allocatable_space = "super",
868   // where "super" is the sum of all block devices for that slot. Since block
869   // devices are dedicated for the corresponding slot, there's no need to halve
870   // the allocatable space.
871   if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
872     return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
873 
874   // On device launching dynamic partitions w/o VAB, regardless of recovery
875   // sideload, super partition must be big enough to hold both A and B slots of
876   // groups. Hence,
877   // allocatable_space = super / 2
878   if (!GetVirtualAbFeatureFlag().IsEnabled())
879     return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
880 
881   // Source build supports VAB. Super partition must be big enough to hold
882   // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
883   // where additional warning messages needs to be written.
884 
885   // If using snapshot updates, implying that target build also uses VAB,
886   // allocatable_space = super
887   if (use_snapshot)
888     return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
889 
890   // Source build supports VAB but not using snapshot updates. There are
891   // several cases, as listed below.
892   // Sideloading: allocatable_space = super.
893   if (IsRecovery())
894     return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
895 
896   // On launch VAB device, this implies secondary payload.
897   // Technically, we don't have to check anything, but sum(groups) < super
898   // still applies.
899   if (!GetVirtualAbFeatureFlag().IsRetrofit())
900     return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
901 
902   // On retrofit VAB device, either of the following:
903   // - downgrading: allocatable_space = super / 2
904   // - secondary payload: don't check anything
905   // These two cases are indistinguishable,
906   // hence emit warning if sum(groups) > super / 2
907   return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
908 }
909 
CheckSuperPartitionAllocatableSpace(android::fs_mgr::MetadataBuilder * builder,const DeltaArchiveManifest & manifest,bool use_snapshot)910 bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
911     android::fs_mgr::MetadataBuilder* builder,
912     const DeltaArchiveManifest& manifest,
913     bool use_snapshot) {
914   uint64_t sum_groups = 0;
915   for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
916     sum_groups += group.size();
917   }
918 
919   uint64_t full_space = builder->AllocatableSpace();
920   uint64_t half_space = full_space / 2;
921   constexpr const char* fmt =
922       "The maximum size of all groups for the target slot (%" PRIu64
923       ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
924   switch (GetSpaceLimit(use_snapshot)) {
925     case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
926       if (sum_groups > half_space) {
927         LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
928         return false;
929       }
930       // If test passes, it implies that the following two conditions also pass.
931       break;
932     }
933     case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
934       if (sum_groups > half_space) {
935         LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
936                      << " This is allowed for downgrade or secondary OTA on "
937                         "retrofit VAB device.";
938       }
939       // still check sum(groups) < super
940       [[fallthrough]];
941     }
942     case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
943       if (sum_groups > full_space) {
944         LOG(ERROR) << base::StringPrintf(fmt, sum_groups, "", full_space);
945         return false;
946       }
947       break;
948     }
949   }
950 
951   return true;
952 }
953 
PrepareSnapshotPartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,uint64_t * required_size)954 bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
955     uint32_t source_slot,
956     uint32_t target_slot,
957     const DeltaArchiveManifest& manifest,
958     uint64_t* required_size) {
959   TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
960 
961   std::string device_dir_str;
962   TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
963   base::FilePath device_dir(device_dir_str);
964   auto super_device =
965       device_dir.Append(GetSuperPartitionName(source_slot)).value();
966   auto builder = LoadMetadataBuilder(super_device, source_slot);
967   if (builder == nullptr) {
968     LOG(ERROR) << "No metadata at "
969                << BootControlInterface::SlotName(source_slot);
970     return false;
971   }
972 
973   TEST_AND_RETURN_FALSE(
974       CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
975 
976   if (!snapshot_->BeginUpdate()) {
977     LOG(ERROR) << "Cannot begin new update.";
978     return false;
979   }
980   auto ret = snapshot_->CreateUpdateSnapshots(manifest);
981   if (!ret) {
982     LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
983     if (required_size != nullptr &&
984         ret.error_code() == Return::ErrorCode::NO_SPACE) {
985       *required_size = ret.required_size();
986     }
987     return false;
988   }
989   return true;
990 }
991 
GetSuperPartitionName(uint32_t slot)992 std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
993     uint32_t slot) {
994   return fs_mgr_get_super_partition_name(slot);
995 }
996 
UpdatePartitionMetadata(MetadataBuilder * builder,uint32_t target_slot,const DeltaArchiveManifest & manifest)997 bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
998     MetadataBuilder* builder,
999     uint32_t target_slot,
1000     const DeltaArchiveManifest& manifest) {
1001   // Check preconditions.
1002   if (GetVirtualAbFeatureFlag().IsEnabled()) {
1003     CHECK(!target_supports_snapshot_ || IsRecovery())
1004         << "Must use snapshot on VAB device when target build supports VAB and "
1005            "not sideloading.";
1006     LOG_IF(INFO, !target_supports_snapshot_)
1007         << "Not using snapshot on VAB device because target build does not "
1008            "support snapshot. Secondary or downgrade OTA?";
1009     LOG_IF(INFO, IsRecovery())
1010         << "Not using snapshot on VAB device because sideloading.";
1011   }
1012 
1013   // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1014   // COW group needs to be deleted to ensure there are enough space to create
1015   // target partitions.
1016   builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1017 
1018   const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1019   DeleteGroupsWithSuffix(builder, target_suffix);
1020 
1021   TEST_AND_RETURN_FALSE(
1022       CheckSuperPartitionAllocatableSpace(builder, manifest, false));
1023 
1024   // name of partition(e.g. "system") -> size in bytes
1025   std::map<std::string, uint64_t> partition_sizes;
1026   for (const auto& partition : manifest.partitions()) {
1027     partition_sizes.emplace(partition.partition_name(),
1028                             partition.new_partition_info().size());
1029   }
1030 
1031   for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1032     auto group_name_suffix = group.name() + target_suffix;
1033     if (!builder->AddGroup(group_name_suffix, group.size())) {
1034       LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
1035                  << group.size();
1036       return false;
1037     }
1038     LOG(INFO) << "Added group " << group_name_suffix << " with size "
1039               << group.size();
1040 
1041     for (const auto& partition_name : group.partition_names()) {
1042       auto partition_sizes_it = partition_sizes.find(partition_name);
1043       if (partition_sizes_it == partition_sizes.end()) {
1044         // TODO(tbao): Support auto-filling partition info for framework-only
1045         // OTA.
1046         LOG(ERROR) << "dynamic_partition_metadata contains partition "
1047                    << partition_name << " but it is not part of the manifest. "
1048                    << "This is not supported.";
1049         return false;
1050       }
1051       uint64_t partition_size = partition_sizes_it->second;
1052 
1053       auto partition_name_suffix = partition_name + target_suffix;
1054       Partition* p = builder->AddPartition(
1055           partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1056       if (!p) {
1057         LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1058                    << " to group " << group_name_suffix;
1059         return false;
1060       }
1061       if (!builder->ResizePartition(p, partition_size)) {
1062         LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
1063                    << " to size " << partition_size << ". Not enough space?";
1064         return false;
1065       }
1066       if (p->size() < partition_size) {
1067         LOG(ERROR) << "Partition " << partition_name_suffix
1068                    << " was expected to have size " << partition_size
1069                    << ", but instead has size " << p->size();
1070         return false;
1071       }
1072       LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
1073                 << group_name_suffix << " with size " << partition_size;
1074     }
1075   }
1076 
1077   return true;
1078 }
1079 
FinishUpdate(bool powerwash_required)1080 bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
1081   if (ExpectMetadataMounted()) {
1082     if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1083       LOG(INFO) << "Snapshot writes are done.";
1084       return snapshot_->FinishedSnapshotWrites(powerwash_required);
1085     }
1086   } else {
1087     LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1088               << "mounted";
1089   }
1090   return true;
1091 }
1092 
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,bool not_in_payload,std::string * device,bool * is_dynamic)1093 bool DynamicPartitionControlAndroid::GetPartitionDevice(
1094     const std::string& partition_name,
1095     uint32_t slot,
1096     uint32_t current_slot,
1097     bool not_in_payload,
1098     std::string* device,
1099     bool* is_dynamic) {
1100   auto partition_dev =
1101       GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
1102   if (!partition_dev.has_value()) {
1103     return false;
1104   }
1105   if (device) {
1106     *device = std::move(partition_dev->rw_device_path);
1107   }
1108   if (is_dynamic) {
1109     *is_dynamic = partition_dev->is_dynamic;
1110   }
1111   return true;
1112 }
1113 
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,std::string * device)1114 bool DynamicPartitionControlAndroid::GetPartitionDevice(
1115     const std::string& partition_name,
1116     uint32_t slot,
1117     uint32_t current_slot,
1118     std::string* device) {
1119   return GetPartitionDevice(
1120       partition_name, slot, current_slot, false, device, nullptr);
1121 }
1122 
GetStaticDevicePath(const base::FilePath & device_dir,const std::string & partition_name_suffixed)1123 static std::string GetStaticDevicePath(
1124     const base::FilePath& device_dir,
1125     const std::string& partition_name_suffixed) {
1126   base::FilePath path = device_dir.Append(partition_name_suffixed);
1127   return path.value();
1128 }
1129 
1130 std::optional<PartitionDevice>
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,bool not_in_payload)1131 DynamicPartitionControlAndroid::GetPartitionDevice(
1132     const std::string& partition_name,
1133     uint32_t slot,
1134     uint32_t current_slot,
1135     bool not_in_payload) {
1136   std::string device_dir_str;
1137   if (!GetDeviceDir(&device_dir_str)) {
1138     LOG(ERROR) << "Failed to GetDeviceDir()";
1139     return {};
1140   }
1141   const base::FilePath device_dir(device_dir_str);
1142   // When VABC is enabled, we can't get device path for dynamic partitions in
1143   // target slot.
1144   const auto& partition_name_suffix =
1145       partition_name + SlotSuffixForSlotNumber(slot);
1146   if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1147       IsDynamicPartition(partition_name, slot)) {
1148     return {
1149         {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1150                                      .Append(partition_name_suffix)
1151                                      .value(),
1152          .is_dynamic = true}};
1153   }
1154 
1155   // When looking up target partition devices, treat them as static if the
1156   // current payload doesn't encode them as dynamic partitions. This may happen
1157   // when applying a retrofit update on top of a dynamic-partitions-enabled
1158   // build.
1159   std::string device;
1160   if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1161       (slot == current_slot || is_target_dynamic_)) {
1162     switch (GetDynamicPartitionDevice(device_dir,
1163                                       partition_name_suffix,
1164                                       slot,
1165                                       current_slot,
1166                                       not_in_payload,
1167                                       &device)) {
1168       case DynamicPartitionDeviceStatus::SUCCESS:
1169         return {{.rw_device_path = device,
1170                  .readonly_device_path = device,
1171                  .is_dynamic = true}};
1172 
1173       case DynamicPartitionDeviceStatus::TRY_STATIC:
1174         break;
1175       case DynamicPartitionDeviceStatus::ERROR:  // fallthrough
1176       default:
1177         return {};
1178     }
1179   }
1180   // Try static partitions.
1181   auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1182   if (!DeviceExists(static_path)) {
1183     LOG(ERROR) << "Device file " << static_path << " does not exist.";
1184     return {};
1185   }
1186 
1187   return {{.rw_device_path = static_path,
1188            .readonly_device_path = static_path,
1189            .is_dynamic = false}};
1190 }
1191 
IsSuperBlockDevice(const base::FilePath & device_dir,uint32_t current_slot,const std::string & partition_name_suffix)1192 bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1193     const base::FilePath& device_dir,
1194     uint32_t current_slot,
1195     const std::string& partition_name_suffix) {
1196   std::string source_device =
1197       device_dir.Append(GetSuperPartitionName(current_slot)).value();
1198   auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1199   return source_metadata->HasBlockDevice(partition_name_suffix);
1200 }
1201 
1202 DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
GetDynamicPartitionDevice(const base::FilePath & device_dir,const std::string & partition_name_suffix,uint32_t slot,uint32_t current_slot,bool not_in_payload,std::string * device)1203 DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1204     const base::FilePath& device_dir,
1205     const std::string& partition_name_suffix,
1206     uint32_t slot,
1207     uint32_t current_slot,
1208     bool not_in_payload,
1209     std::string* device) {
1210   std::string super_device =
1211       device_dir.Append(GetSuperPartitionName(slot)).value();
1212 
1213   auto builder = LoadMetadataBuilder(super_device, slot);
1214   if (builder == nullptr) {
1215     LOG(ERROR) << "No metadata in slot "
1216                << BootControlInterface::SlotName(slot);
1217     return DynamicPartitionDeviceStatus::ERROR;
1218   }
1219   if (builder->FindPartition(partition_name_suffix) == nullptr) {
1220     LOG(INFO) << partition_name_suffix
1221               << " is not in super partition metadata.";
1222 
1223     if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1224       LOG(ERROR) << "The static partition " << partition_name_suffix
1225                  << " is a block device for current metadata."
1226                  << "It cannot be used as a logical partition.";
1227       return DynamicPartitionDeviceStatus::ERROR;
1228     }
1229 
1230     return DynamicPartitionDeviceStatus::TRY_STATIC;
1231   }
1232 
1233   if (slot == current_slot) {
1234     if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1235       LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1236                    << "not mapped. Now try to map it.";
1237     } else {
1238       if (GetDmDevicePathByName(partition_name_suffix, device)) {
1239         LOG(INFO) << partition_name_suffix
1240                   << " is mapped on device mapper: " << *device;
1241         return DynamicPartitionDeviceStatus::SUCCESS;
1242       }
1243       LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1244       return DynamicPartitionDeviceStatus::ERROR;
1245     }
1246   }
1247 
1248   bool force_writable = (slot != current_slot) && !not_in_payload;
1249   if (MapPartitionOnDeviceMapper(
1250           super_device, partition_name_suffix, slot, force_writable, device)) {
1251     return DynamicPartitionDeviceStatus::SUCCESS;
1252   }
1253   return DynamicPartitionDeviceStatus::ERROR;
1254 }
1255 
set_fake_mapped_devices(const std::set<std::string> & fake)1256 void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1257     const std::set<std::string>& fake) {
1258   mapped_devices_ = fake;
1259 }
1260 
IsRecovery()1261 bool DynamicPartitionControlAndroid::IsRecovery() {
1262   return constants::kIsRecovery;
1263 }
1264 
IsIncrementalUpdate(const DeltaArchiveManifest & manifest)1265 static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1266   const auto& partitions = manifest.partitions();
1267   return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1268     return p.has_old_partition_info();
1269   });
1270 }
1271 
DeleteSourcePartitions(MetadataBuilder * builder,uint32_t source_slot,const DeltaArchiveManifest & manifest)1272 bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1273     MetadataBuilder* builder,
1274     uint32_t source_slot,
1275     const DeltaArchiveManifest& manifest) {
1276   TEST_AND_RETURN_FALSE(IsRecovery());
1277 
1278   if (IsIncrementalUpdate(manifest)) {
1279     LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1280                << "be created.";
1281     if (GetVirtualAbFeatureFlag().IsLaunch()) {
1282       LOG(ERROR) << "Sideloading incremental updates on devices launches "
1283                  << " Virtual A/B is not supported.";
1284     }
1285     return false;
1286   }
1287 
1288   LOG(INFO) << "Will overwrite existing partitions. Slot "
1289             << BootControlInterface::SlotName(source_slot)
1290             << " may be unbootable until update finishes!";
1291   const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1292   DeleteGroupsWithSuffix(builder, source_suffix);
1293 
1294   return true;
1295 }
1296 
1297 std::unique_ptr<AbstractAction>
GetCleanupPreviousUpdateAction(BootControlInterface * boot_control,PrefsInterface * prefs,CleanupPreviousUpdateActionDelegateInterface * delegate)1298 DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1299     BootControlInterface* boot_control,
1300     PrefsInterface* prefs,
1301     CleanupPreviousUpdateActionDelegateInterface* delegate) {
1302   if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1303     return std::make_unique<NoOpAction>();
1304   }
1305   return std::make_unique<CleanupPreviousUpdateAction>(
1306       prefs, boot_control, snapshot_.get(), delegate);
1307 }
1308 
ResetUpdate(PrefsInterface * prefs)1309 bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1310   if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1311     return true;
1312   }
1313   for (auto& list : dynamic_partition_list_) {
1314     list.clear();
1315   }
1316 
1317   LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1318   TEST_AND_RETURN_FALSE(prefs != nullptr);
1319 
1320   // If the device has already booted into the target slot,
1321   // ResetUpdateProgress may pass but CancelUpdate fails.
1322   // This is expected. A scheduled CleanupPreviousUpdateAction should free
1323   // space when it is done.
1324   TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1325       prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1326 
1327   if (ExpectMetadataMounted()) {
1328     TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1329   } else {
1330     LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1331               << "not mounted";
1332   }
1333 
1334   return true;
1335 }
1336 
ListDynamicPartitionsForSlot(uint32_t slot,uint32_t current_slot,std::vector<std::string> * partitions)1337 bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1338     uint32_t slot,
1339     uint32_t current_slot,
1340     std::vector<std::string>* partitions) {
1341   CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1342       << " source slot: " << source_slot_ << " target slot: " << target_slot_
1343       << " slot: " << slot
1344       << " attempting to query dynamic partition metadata for target slot "
1345          "before PreparePartitionForUpdate() is called. The "
1346          "metadata in target slot isn't valid until "
1347          "PreparePartitionForUpdate() is called, contining execution would "
1348          "likely cause problems.";
1349   bool slot_enables_dynamic_partitions =
1350       GetDynamicPartitionsFeatureFlag().IsEnabled();
1351   // Check if the target slot has dynamic partitions, this may happen when
1352   // applying a retrofit package.
1353   if (slot != current_slot) {
1354     slot_enables_dynamic_partitions =
1355         slot_enables_dynamic_partitions && is_target_dynamic_;
1356   }
1357 
1358   if (!slot_enables_dynamic_partitions) {
1359     LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1360     return true;
1361   }
1362 
1363   std::string device_dir_str;
1364   TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1365   base::FilePath device_dir(device_dir_str);
1366   auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1367   auto builder = LoadMetadataBuilder(super_device, slot);
1368   TEST_AND_RETURN_FALSE(builder != nullptr);
1369 
1370   std::vector<std::string> result;
1371   auto suffix = SlotSuffixForSlotNumber(slot);
1372   for (const auto& group : builder->ListGroups()) {
1373     for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1374       std::string_view partition_name = partition->name();
1375       if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1376         continue;
1377       }
1378       result.emplace_back(partition_name);
1379     }
1380   }
1381   *partitions = std::move(result);
1382   return true;
1383 }
1384 
VerifyExtentsForUntouchedPartitions(uint32_t source_slot,uint32_t target_slot,const std::vector<std::string> & partitions)1385 bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1386     uint32_t source_slot,
1387     uint32_t target_slot,
1388     const std::vector<std::string>& partitions) {
1389   std::string device_dir_str;
1390   TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1391   base::FilePath device_dir(device_dir_str);
1392 
1393   auto source_super_device =
1394       device_dir.Append(GetSuperPartitionName(source_slot)).value();
1395   auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1396   TEST_AND_RETURN_FALSE(source_builder != nullptr);
1397 
1398   auto target_super_device =
1399       device_dir.Append(GetSuperPartitionName(target_slot)).value();
1400   auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1401   TEST_AND_RETURN_FALSE(target_builder != nullptr);
1402 
1403   return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1404       *source_builder, source_slot, *target_builder, target_slot, partitions);
1405 }
1406 
ExpectMetadataMounted()1407 bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1408   // No need to mount metadata for non-Virtual A/B devices.
1409   if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1410     return false;
1411   }
1412   // Intentionally not checking |metadata_device_| in Android mode.
1413   // /metadata should always be mounted in Android mode. If it isn't, let caller
1414   // fails when calling into SnapshotManager.
1415   if (!IsRecovery()) {
1416     return true;
1417   }
1418   // In recovery mode, explicitly check |metadata_device_|.
1419   return metadata_device_ != nullptr;
1420 }
1421 
EnsureMetadataMounted()1422 bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1423   // No need to mount metadata for non-Virtual A/B devices.
1424   if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1425     return true;
1426   }
1427 
1428   if (metadata_device_ == nullptr) {
1429     metadata_device_ = snapshot_->EnsureMetadataMounted();
1430   }
1431   return metadata_device_ != nullptr;
1432 }
1433 
1434 std::unique_ptr<android::snapshot::ICowWriter>
OpenCowWriter(const std::string & partition_name,const std::optional<std::string> & source_path,std::optional<uint64_t> label)1435 DynamicPartitionControlAndroid::OpenCowWriter(
1436     const std::string& partition_name,
1437     const std::optional<std::string>& source_path,
1438     std::optional<uint64_t> label) {
1439   auto suffix = SlotSuffixForSlotNumber(target_slot_);
1440 
1441   auto super_device = GetSuperDevice();
1442   if (!super_device.has_value()) {
1443     return nullptr;
1444   }
1445   CreateLogicalPartitionParams params = {
1446       .block_device = super_device->value(),
1447       .metadata_slot = target_slot_,
1448       .partition_name = partition_name + suffix,
1449       .force_writable = true,
1450       .timeout_ms = kMapSnapshotTimeout};
1451   // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1452   // it.
1453   return snapshot_->OpenSnapshotWriter(params, label);
1454 }  // namespace chromeos_update_engine
1455 
OpenCowFd(const std::string & unsuffixed_partition_name,const std::optional<std::string> & source_path,bool is_append)1456 std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
1457     const std::string& unsuffixed_partition_name,
1458     const std::optional<std::string>& source_path,
1459     bool is_append) {
1460   auto cow_writer = OpenCowWriter(
1461       unsuffixed_partition_name, source_path, {kEndOfInstallLabel});
1462   if (cow_writer == nullptr) {
1463     LOG(ERROR) << "OpenCowWriter failed";
1464     return nullptr;
1465   }
1466   auto fd = cow_writer->OpenFileDescriptor(source_path);
1467   if (fd == nullptr) {
1468     LOG(ERROR) << "ICowReader::OpenFileDescriptor failed";
1469     return nullptr;
1470   }
1471   return std::make_unique<CowWriterFileDescriptor>(
1472       std::move(cow_writer), std::move(fd), source_path);
1473 }
1474 
GetSuperDevice()1475 std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1476   std::string device_dir_str;
1477   if (!GetDeviceDir(&device_dir_str)) {
1478     LOG(ERROR) << "Failed to get device dir!";
1479     return {};
1480   }
1481   base::FilePath device_dir(device_dir_str);
1482   auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1483   return super_device;
1484 }
1485 
MapAllPartitions()1486 bool DynamicPartitionControlAndroid::MapAllPartitions() {
1487   return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
1488 }
1489 
IsDynamicPartition(const std::string & partition_name,uint32_t slot)1490 bool DynamicPartitionControlAndroid::IsDynamicPartition(
1491     const std::string& partition_name, uint32_t slot) {
1492   if (slot >= dynamic_partition_list_.size()) {
1493     LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1494                << dynamic_partition_list_.size() << " slots";
1495     return false;
1496   }
1497   auto& dynamic_partition_list = dynamic_partition_list_[slot];
1498   if (dynamic_partition_list.empty() &&
1499       GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1500     // Use the DAP config of the target slot.
1501     CHECK(ListDynamicPartitionsForSlot(
1502         slot, source_slot_, &dynamic_partition_list));
1503   }
1504   return std::find(dynamic_partition_list.begin(),
1505                    dynamic_partition_list.end(),
1506                    partition_name) != dynamic_partition_list.end();
1507 }
1508 
UpdateUsesSnapshotCompression()1509 bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
1510   return GetVirtualAbFeatureFlag().IsEnabled() &&
1511          snapshot_->UpdateUsesCompression();
1512 }
1513 
1514 FeatureFlag
GetVirtualAbUserspaceSnapshotsFeatureFlag()1515 DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1516   return virtual_ab_userspace_snapshots_;
1517 }
1518 
1519 }  // namespace chromeos_update_engine
1520