blob: 29ba44c1fbdf7c46272d5b2206eed1050874d063 [file] [log] [blame]
Kelvin Zhang596a3202022-03-07 14:13:42 -08001//
2// Copyright (C) 2022 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
Kelvin Zhang91e839c2022-04-05 14:25:00 -070017#include <array>
Kelvin Zhang596a3202022-03-07 14:13:42 -080018#include <cstdint>
19#include <cstdio>
Juhyung Parkc8c00572024-07-09 22:47:09 +090020#include <future>
Kelvin Zhangc7515d42022-03-23 10:44:16 -070021#include <iterator>
Kelvin Zhang596a3202022-03-07 14:13:42 -080022#include <memory>
23
Kelvin Zhang91e839c2022-04-05 14:25:00 -070024#include <fcntl.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080025#include <sys/mman.h>
26#include <sys/stat.h>
27
Kelvin Zhangc7515d42022-03-23 10:44:16 -070028#include <android-base/strings.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080029#include <base/files/file_path.h>
30#include <gflags/gflags.h>
31#include <unistd.h>
Kelvin Zhang91e839c2022-04-05 14:25:00 -070032#include <xz.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080033
34#include "update_engine/common/utils.h"
35#include "update_engine/common/hash_calculator.h"
36#include "update_engine/payload_consumer/file_descriptor.h"
Kelvin Zhang91e839c2022-04-05 14:25:00 -070037#include "update_engine/payload_consumer/file_descriptor_utils.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080038#include "update_engine/payload_consumer/install_operation_executor.h"
39#include "update_engine/payload_consumer/payload_metadata.h"
Kelvin Zhang91e839c2022-04-05 14:25:00 -070040#include "update_engine/payload_consumer/verity_writer_android.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080041#include "update_engine/update_metadata.pb.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080042
43DEFINE_string(payload, "", "Path to payload.bin");
Kelvin Zhang91e839c2022-04-05 14:25:00 -070044DEFINE_string(
45 input_dir,
46 "",
47 "Directory to read input images. Only required for incremental OTAs");
Kelvin Zhang596a3202022-03-07 14:13:42 -080048DEFINE_string(output_dir, "", "Directory to put output images");
49DEFINE_int64(payload_offset,
50 0,
51 "Offset to start of payload.bin. Useful if payload path actually "
52 "points to a .zip file containing payload.bin");
Kelvin Zhangc7515d42022-03-23 10:44:16 -070053DEFINE_string(partitions,
54 "",
55 "Comma separated list of partitions to extract, leave empty for "
56 "extracting all partitions");
Juhyung Parkc8c00572024-07-09 22:47:09 +090057DEFINE_bool(single_thread, false, "Limit extraction to a single thread");
Kelvin Zhang596a3202022-03-07 14:13:42 -080058
59using chromeos_update_engine::DeltaArchiveManifest;
60using chromeos_update_engine::PayloadMetadata;
61
62namespace chromeos_update_engine {
63
Kelvin Zhang91e839c2022-04-05 14:25:00 -070064void WriteVerity(const PartitionUpdate& partition,
65 FileDescriptorPtr fd,
66 const size_t block_size) {
67 // 512KB buffer, arbitrary value. Larger buffers may improve performance.
68 static constexpr size_t BUFFER_SIZE = 1024 * 512;
69 if (partition.hash_tree_extent().num_blocks() == 0 &&
70 partition.fec_extent().num_blocks() == 0) {
71 return;
72 }
73 InstallPlan::Partition install_part;
74 install_part.block_size = block_size;
75 CHECK(install_part.ParseVerityConfig(partition));
76 VerityWriterAndroid writer;
77 CHECK(writer.Init(install_part));
78 std::array<uint8_t, BUFFER_SIZE> buffer;
79 const auto data_size =
80 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
81 size_t offset = 0;
82 while (offset < data_size) {
83 const auto bytes_to_read =
84 static_cast<ssize_t>(std::min(BUFFER_SIZE, data_size - offset));
85 ssize_t bytes_read;
86 CHECK(
87 utils::ReadAll(fd, buffer.data(), bytes_to_read, offset, &bytes_read));
88 CHECK_EQ(bytes_read, bytes_to_read)
89 << " Failed to read at offset " << offset << " "
90 << android::base::ErrnoNumberAsString(errno);
91 writer.Update(offset, buffer.data(), bytes_read);
92 offset += bytes_read;
93 }
94 CHECK(writer.Finalize(fd.get(), fd.get()));
95 return;
96}
97
Juhyung Park202dee22024-07-09 22:39:11 +090098bool ExtractImageFromPartition(const DeltaArchiveManifest& manifest,
99 const PartitionUpdate& partition,
100 const size_t data_begin,
101 int payload_fd,
102 std::string_view input_dir,
103 std::string_view output_dir) {
104 InstallOperationExecutor executor(manifest.block_size());
105 const base::FilePath output_dir_path(
106 base::StringPiece(output_dir.data(), output_dir.size()));
107 const base::FilePath input_dir_path(
108 base::StringPiece(input_dir.data(), input_dir.size()));
109 std::vector<unsigned char> blob;
110
111 LOG(INFO) << "Extracting partition " << partition.partition_name()
112 << " size: " << partition.new_partition_info().size();
113 const auto output_path =
114 output_dir_path.Append(partition.partition_name() + ".img").value();
115 auto out_fd =
116 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
117 TEST_AND_RETURN_FALSE_ERRNO(
118 out_fd->Open(output_path.c_str(), O_RDWR | O_CREAT, 0644));
119 auto in_fd =
120 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
121 if (partition.has_old_partition_info()) {
122 const auto input_path =
123 input_dir_path.Append(partition.partition_name() + ".img").value();
124 LOG(INFO) << "Incremental OTA detected for partition "
125 << partition.partition_name() << " opening source image "
126 << input_path;
127 CHECK(in_fd->Open(input_path.c_str(), O_RDONLY))
128 << " failed to open " << input_path;
129 }
130
131 for (const auto& op : partition.operations()) {
132 if (op.has_src_sha256_hash()) {
133 brillo::Blob actual_hash;
134 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
135 in_fd, op.src_extents(), manifest.block_size(), &actual_hash));
136 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
Juhyung Parkee293ba2024-07-09 23:46:20 +0900137 HexEncode(op.src_sha256_hash()))
138 << ", failed partition: " << partition.partition_name();
Juhyung Park202dee22024-07-09 22:39:11 +0900139 }
140
141 blob.resize(op.data_length());
142 const auto op_data_offset = data_begin + op.data_offset();
143 ssize_t bytes_read = 0;
144 TEST_AND_RETURN_FALSE(utils::PReadAll(
145 payload_fd, blob.data(), blob.size(), op_data_offset, &bytes_read));
146 if (op.has_data_sha256_hash()) {
147 brillo::Blob actual_hash;
148 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(blob, &actual_hash));
149 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
Juhyung Parkee293ba2024-07-09 23:46:20 +0900150 HexEncode(op.data_sha256_hash()))
151 << ", failed partition: " << partition.partition_name();
Juhyung Park202dee22024-07-09 22:39:11 +0900152 }
153 auto direct_writer = std::make_unique<DirectExtentWriter>(out_fd);
154 if (op.type() == InstallOperation::ZERO) {
155 TEST_AND_RETURN_FALSE(
156 executor.ExecuteZeroOrDiscardOperation(op, std::move(direct_writer)));
157 } else if (op.type() == InstallOperation::REPLACE ||
158 op.type() == InstallOperation::REPLACE_BZ ||
159 op.type() == InstallOperation::REPLACE_XZ) {
160 TEST_AND_RETURN_FALSE(executor.ExecuteReplaceOperation(
161 op, std::move(direct_writer), blob.data()));
162 } else if (op.type() == InstallOperation::SOURCE_COPY) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900163 CHECK(in_fd->IsOpen())
164 << ", failed partition: " << partition.partition_name();
Juhyung Park202dee22024-07-09 22:39:11 +0900165 TEST_AND_RETURN_FALSE(executor.ExecuteSourceCopyOperation(
166 op, std::move(direct_writer), in_fd));
167 } else {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900168 CHECK(in_fd->IsOpen())
169 << ", failed partition: " << partition.partition_name();
Juhyung Park202dee22024-07-09 22:39:11 +0900170 TEST_AND_RETURN_FALSE(executor.ExecuteDiffOperation(
171 op, std::move(direct_writer), in_fd, blob.data(), blob.size()));
172 }
173 }
174 WriteVerity(partition, out_fd, manifest.block_size());
175 int err =
176 truncate64(output_path.c_str(), partition.new_partition_info().size());
177 if (err) {
178 PLOG(ERROR) << "Failed to truncate " << output_path << " to "
179 << partition.new_partition_info().size();
180 }
181 brillo::Blob actual_hash;
182 TEST_AND_RETURN_FALSE(
183 HashCalculator::RawHashOfFile(output_path, &actual_hash));
184 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
185 HexEncode(partition.new_partition_info().hash()))
186 << " Partition " << partition.partition_name()
187 << " hash mismatches. Either the source image or OTA package is "
188 "corrupted.";
189
Juhyung Parkee293ba2024-07-09 23:46:20 +0900190 LOG(INFO) << "Extracted partition " << partition.partition_name();
191
Juhyung Park202dee22024-07-09 22:39:11 +0900192 return true;
193}
194
Kelvin Zhang596a3202022-03-07 14:13:42 -0800195bool ExtractImagesFromOTA(const DeltaArchiveManifest& manifest,
196 const PayloadMetadata& metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700197 int payload_fd,
198 size_t payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700199 std::string_view input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700200 std::string_view output_dir,
201 const std::set<std::string>& partitions) {
Kelvin Zhangb9368922022-03-17 21:11:32 -0700202 const size_t data_begin = metadata.GetMetadataSize() +
203 metadata.GetMetadataSignatureSize() +
204 payload_offset;
Juhyung Parkee293ba2024-07-09 23:46:20 +0900205 bool ret = true;
Juhyung Park202dee22024-07-09 22:39:11 +0900206
Juhyung Parkc8c00572024-07-09 22:47:09 +0900207 if (FLAGS_single_thread) {
208 for (const auto& partition : manifest.partitions()) {
Kelvin Zhang99da2212024-09-27 17:24:19 -0700209 if (!partitions.empty() &&
210 partitions.count(partition.partition_name()) == 0) {
211 continue;
212 }
Juhyung Parkc8c00572024-07-09 22:47:09 +0900213 if (!ExtractImageFromPartition(manifest,
214 partition,
215 data_begin,
216 payload_fd,
217 input_dir,
218 output_dir)) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900219 ret = false;
220 LOG(ERROR) << "Extraction of partition " << partition.partition_name()
221 << " failed";
222 break;
Juhyung Parkc8c00572024-07-09 22:47:09 +0900223 }
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700224 }
Juhyung Parkc8c00572024-07-09 22:47:09 +0900225 } else {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900226 std::vector<std::pair<std::future<bool>, std::string>> futures;
Juhyung Parkc8c00572024-07-09 22:47:09 +0900227 for (const auto& partition : manifest.partitions()) {
Kelvin Zhang99da2212024-09-27 17:24:19 -0700228 if (!partitions.empty() &&
229 partitions.count(partition.partition_name()) == 0) {
230 continue;
231 }
Juhyung Parkee293ba2024-07-09 23:46:20 +0900232 futures.push_back(std::make_pair(std::async(std::launch::async,
233 ExtractImageFromPartition,
234 manifest,
235 partition,
236 data_begin,
237 payload_fd,
238 input_dir,
239 output_dir),
240 partition.partition_name()));
Juhyung Parkc8c00572024-07-09 22:47:09 +0900241 }
242 for (auto& future : futures) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900243 if (!future.first.get()) {
244 ret = false;
245 LOG(ERROR) << "Extraction of partition " << future.second << " failed";
Juhyung Parkc8c00572024-07-09 22:47:09 +0900246 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800247 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800248 }
Juhyung Parkee293ba2024-07-09 23:46:20 +0900249 return ret;
Kelvin Zhang596a3202022-03-07 14:13:42 -0800250}
251
252} // namespace chromeos_update_engine
253
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700254namespace {
255
256bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
257 for (const auto& part : manifest.partitions()) {
258 if (part.has_old_partition_info()) {
259 return true;
260 }
261 }
262 return false;
263}
264
265} // namespace
266
Kelvin Zhang596a3202022-03-07 14:13:42 -0800267int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700268 gflags::SetUsageMessage(
269 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800270 gflags::ParseCommandLineFlags(&argc, &argv, true);
271 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700272 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
273 const std::set<std::string> partitions(
274 std::make_move_iterator(tokens.begin()),
275 std::make_move_iterator(tokens.end()));
276 if (FLAGS_payload.empty()) {
277 LOG(ERROR) << "--payload <payload path> is required";
278 return 1;
279 }
280 if (!partitions.empty()) {
281 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
282 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800283 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
284 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700285 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800286 return 1;
287 }
288 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
289 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
290 if (payload_size <= 0) {
291 PLOG(ERROR)
292 << "Couldn't determine size of payload file, or payload file is empty";
293 return 1;
294 }
295
296 PayloadMetadata payload_metadata;
297 auto payload = static_cast<unsigned char*>(
298 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
299
300 if (payload == MAP_FAILED) {
301 PLOG(ERROR) << "Failed to mmap() payload file";
302 return 1;
303 }
304
305 auto munmap_deleter = [payload_size](auto payload) {
306 munmap(payload, payload_size);
307 };
308 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
309 payload, munmap_deleter};
310 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
311 payload_size - FLAGS_payload_offset,
312 nullptr) !=
313 chromeos_update_engine::MetadataParseResult::kSuccess) {
314 LOG(ERROR) << "Payload header parse failed!";
315 return 1;
316 }
317 DeltaArchiveManifest manifest;
318 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
319 payload_size - FLAGS_payload_offset,
320 &manifest)) {
321 LOG(ERROR) << "Failed to parse manifest!";
322 return 1;
323 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700324 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
325 LOG(ERROR) << FLAGS_payload
326 << " is an incremental OTA, --input_dir parameter is required.";
327 return 1;
328 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800329 return !ExtractImagesFromOTA(manifest,
330 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700331 payload_fd,
332 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700333 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700334 FLAGS_output_dir,
335 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800336}