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 #include "flashing.h"
17
18 #include <fcntl.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22
23 #include <algorithm>
24 #include <memory>
25 #include <optional>
26 #include <set>
27 #include <string>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/strings.h>
33 #include <ext4_utils/ext4_utils.h>
34 #include <fs_mgr_overlayfs.h>
35 #include <fstab/fstab.h>
36 #include <libavb/libavb.h>
37 #include <liblp/builder.h>
38 #include <liblp/liblp.h>
39 #include <libsnapshot/snapshot.h>
40 #include <sparse/sparse.h>
41
42 #include "fastboot_device.h"
43 #include "utility.h"
44
45 using namespace android::fs_mgr;
46 using namespace std::literals;
47
48 namespace {
49
50 constexpr uint32_t SPARSE_HEADER_MAGIC = 0xed26ff3a;
51
WipeOverlayfsForPartition(FastbootDevice * device,const std::string & partition_name)52 void WipeOverlayfsForPartition(FastbootDevice* device, const std::string& partition_name) {
53 // May be called, in the case of sparse data, multiple times so cache/skip.
54 static std::set<std::string> wiped;
55 if (wiped.find(partition_name) != wiped.end()) return;
56 wiped.insert(partition_name);
57 // Following appears to have a first time 2% impact on flashing speeds.
58
59 // Convert partition_name to a validated mount point and wipe.
60 Fstab fstab;
61 ReadDefaultFstab(&fstab);
62
63 std::optional<AutoMountMetadata> mount_metadata;
64 for (const auto& entry : fstab) {
65 auto partition = android::base::Basename(entry.mount_point);
66 if ("/" == entry.mount_point) {
67 partition = "system";
68 }
69
70 if ((partition + device->GetCurrentSlot()) == partition_name) {
71 mount_metadata.emplace();
72 android::fs_mgr::TeardownAllOverlayForMountPoint(entry.mount_point);
73 }
74 }
75 }
76
77 } // namespace
78
FlashRawDataChunk(PartitionHandle * handle,const char * data,size_t len)79 int FlashRawDataChunk(PartitionHandle* handle, const char* data, size_t len) {
80 size_t ret = 0;
81 const size_t max_write_size = 1048576;
82 void* aligned_buffer;
83
84 if (posix_memalign(&aligned_buffer, 4096, max_write_size)) {
85 PLOG(ERROR) << "Failed to allocate write buffer";
86 return -ENOMEM;
87 }
88
89 auto aligned_buffer_unique_ptr = std::unique_ptr<void, decltype(&free)>{aligned_buffer, free};
90
91 while (ret < len) {
92 int this_len = std::min(max_write_size, len - ret);
93 memcpy(aligned_buffer_unique_ptr.get(), data, this_len);
94 // In case of non 4KB aligned writes, reopen without O_DIRECT flag
95 if (this_len & 0xFFF) {
96 if (handle->Reset(O_WRONLY) != true) {
97 PLOG(ERROR) << "Failed to reset file descriptor";
98 return -1;
99 }
100 }
101
102 int this_ret = write(handle->fd(), aligned_buffer_unique_ptr.get(), this_len);
103 if (this_ret < 0) {
104 PLOG(ERROR) << "Failed to flash data of len " << len;
105 return -1;
106 }
107 data += this_ret;
108 ret += this_ret;
109 }
110 return 0;
111 }
112
FlashRawData(PartitionHandle * handle,const std::vector<char> & downloaded_data)113 int FlashRawData(PartitionHandle* handle, const std::vector<char>& downloaded_data) {
114 int ret = FlashRawDataChunk(handle, downloaded_data.data(), downloaded_data.size());
115 if (ret < 0) {
116 return -errno;
117 }
118 return ret;
119 }
120
WriteCallback(void * priv,const void * data,size_t len)121 int WriteCallback(void* priv, const void* data, size_t len) {
122 PartitionHandle* handle = reinterpret_cast<PartitionHandle*>(priv);
123 if (!data) {
124 return lseek64(handle->fd(), len, SEEK_CUR) >= 0 ? 0 : -errno;
125 }
126 return FlashRawDataChunk(handle, reinterpret_cast<const char*>(data), len);
127 }
128
FlashSparseData(PartitionHandle * handle,std::vector<char> & downloaded_data)129 int FlashSparseData(PartitionHandle* handle, std::vector<char>& downloaded_data) {
130 struct sparse_file* file = sparse_file_import_buf(downloaded_data.data(),
131 downloaded_data.size(), true, false);
132 if (!file) {
133 // Invalid sparse format
134 return -EINVAL;
135 }
136 return sparse_file_callback(file, false, false, WriteCallback, reinterpret_cast<void*>(handle));
137 }
138
FlashBlockDevice(PartitionHandle * handle,std::vector<char> & downloaded_data)139 int FlashBlockDevice(PartitionHandle* handle, std::vector<char>& downloaded_data) {
140 lseek64(handle->fd(), 0, SEEK_SET);
141 if (downloaded_data.size() >= sizeof(SPARSE_HEADER_MAGIC) &&
142 *reinterpret_cast<uint32_t*>(downloaded_data.data()) == SPARSE_HEADER_MAGIC) {
143 return FlashSparseData(handle, downloaded_data);
144 } else {
145 return FlashRawData(handle, downloaded_data);
146 }
147 }
148
CopyAVBFooter(std::vector<char> * data,const uint64_t block_device_size)149 static void CopyAVBFooter(std::vector<char>* data, const uint64_t block_device_size) {
150 if (data->size() < AVB_FOOTER_SIZE) {
151 return;
152 }
153 std::string footer;
154 uint64_t footer_offset = data->size() - AVB_FOOTER_SIZE;
155 for (int idx = 0; idx < AVB_FOOTER_MAGIC_LEN; idx++) {
156 footer.push_back(data->at(footer_offset + idx));
157 }
158 if (0 != footer.compare(AVB_FOOTER_MAGIC)) {
159 return;
160 }
161
162 // copy AVB footer from end of data to end of block device
163 uint64_t original_data_size = data->size();
164 data->resize(block_device_size, 0);
165 for (int idx = 0; idx < AVB_FOOTER_SIZE; idx++) {
166 data->at(block_device_size - 1 - idx) = data->at(original_data_size - 1 - idx);
167 }
168 }
169
Flash(FastbootDevice * device,const std::string & partition_name)170 int Flash(FastbootDevice* device, const std::string& partition_name) {
171 PartitionHandle handle;
172 if (!OpenPartition(device, partition_name, &handle, O_WRONLY | O_DIRECT)) {
173 return -ENOENT;
174 }
175
176 std::vector<char> data = std::move(device->download_data());
177 if (data.size() == 0) {
178 return -EINVAL;
179 }
180 uint64_t block_device_size = get_block_device_size(handle.fd());
181 if (data.size() > block_device_size) {
182 return -EOVERFLOW;
183 } else if (data.size() < block_device_size &&
184 (partition_name == "boot" || partition_name == "boot_a" ||
185 partition_name == "boot_b" || partition_name == "init_boot" ||
186 partition_name == "init_boot_a" || partition_name == "init_boot_b")) {
187 CopyAVBFooter(&data, block_device_size);
188 }
189 if (android::base::GetProperty("ro.system.build.type", "") != "user") {
190 WipeOverlayfsForPartition(device, partition_name);
191 }
192 int result = FlashBlockDevice(&handle, data);
193 sync();
194 return result;
195 }
196
RemoveScratchPartition()197 static void RemoveScratchPartition() {
198 AutoMountMetadata mount_metadata;
199 android::fs_mgr::TeardownAllOverlayForMountPoint();
200 }
201
UpdateSuper(FastbootDevice * device,const std::string & super_name,bool wipe)202 bool UpdateSuper(FastbootDevice* device, const std::string& super_name, bool wipe) {
203 std::vector<char> data = std::move(device->download_data());
204 if (data.empty()) {
205 return device->WriteFail("No data available");
206 }
207
208 std::unique_ptr<LpMetadata> new_metadata = ReadFromImageBlob(data.data(), data.size());
209 if (!new_metadata) {
210 return device->WriteFail("Data is not a valid logical partition metadata image");
211 }
212
213 if (!FindPhysicalPartition(super_name)) {
214 return device->WriteFail("Cannot find " + super_name +
215 ", build may be missing broken or missing boot_devices");
216 }
217
218 std::string slot_suffix = device->GetCurrentSlot();
219 uint32_t slot_number = SlotNumberForSlotSuffix(slot_suffix);
220
221 std::string other_slot_suffix;
222 if (!slot_suffix.empty()) {
223 other_slot_suffix = (slot_suffix == "_a") ? "_b" : "_a";
224 }
225
226 // If we are unable to read the existing metadata, then the super partition
227 // is corrupt. In this case we reflash the whole thing using the provided
228 // image.
229 std::unique_ptr<LpMetadata> old_metadata = ReadMetadata(super_name, slot_number);
230 if (wipe || !old_metadata) {
231 if (!FlashPartitionTable(super_name, *new_metadata.get())) {
232 return device->WriteFail("Unable to flash new partition table");
233 }
234 RemoveScratchPartition();
235 sync();
236 return device->WriteOkay("Successfully flashed partition table");
237 }
238
239 std::set<std::string> partitions_to_keep;
240 bool virtual_ab = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
241 for (const auto& partition : old_metadata->partitions) {
242 // Preserve partitions in the other slot, but not the current slot.
243 std::string partition_name = GetPartitionName(partition);
244 if (!slot_suffix.empty()) {
245 auto part_suffix = GetPartitionSlotSuffix(partition_name);
246 if (part_suffix == slot_suffix || (part_suffix == other_slot_suffix && virtual_ab)) {
247 continue;
248 }
249 }
250 std::string group_name = GetPartitionGroupName(old_metadata->groups[partition.group_index]);
251 // Skip partitions in the COW group
252 if (group_name == android::snapshot::kCowGroupName) {
253 continue;
254 }
255 partitions_to_keep.emplace(partition_name);
256 }
257
258 // Do not preserve the scratch partition.
259 partitions_to_keep.erase("scratch");
260
261 if (!partitions_to_keep.empty()) {
262 std::unique_ptr<MetadataBuilder> builder = MetadataBuilder::New(*new_metadata.get());
263 if (!builder->ImportPartitions(*old_metadata.get(), partitions_to_keep)) {
264 return device->WriteFail(
265 "Old partitions are not compatible with the new super layout; wipe needed");
266 }
267
268 new_metadata = builder->Export();
269 if (!new_metadata) {
270 return device->WriteFail("Unable to build new partition table; wipe needed");
271 }
272 }
273
274 // Write the new table to every metadata slot.
275 if (!UpdateAllPartitionMetadata(device, super_name, *new_metadata.get())) {
276 return device->WriteFail("Unable to write new partition table");
277 }
278 RemoveScratchPartition();
279 sync();
280 return device->WriteOkay("Successfully updated partition table");
281 }
282