blob: 42270f4b73e5140eee7fb7aea97560ebb1869b21 [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()) {
209 if (!ExtractImageFromPartition(manifest,
210 partition,
211 data_begin,
212 payload_fd,
213 input_dir,
214 output_dir)) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900215 ret = false;
216 LOG(ERROR) << "Extraction of partition " << partition.partition_name()
217 << " failed";
218 break;
Juhyung Parkc8c00572024-07-09 22:47:09 +0900219 }
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700220 }
Juhyung Parkc8c00572024-07-09 22:47:09 +0900221 } else {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900222 std::vector<std::pair<std::future<bool>, std::string>> futures;
Juhyung Parkc8c00572024-07-09 22:47:09 +0900223 for (const auto& partition : manifest.partitions()) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900224 futures.push_back(std::make_pair(std::async(std::launch::async,
225 ExtractImageFromPartition,
226 manifest,
227 partition,
228 data_begin,
229 payload_fd,
230 input_dir,
231 output_dir),
232 partition.partition_name()));
Juhyung Parkc8c00572024-07-09 22:47:09 +0900233 }
234 for (auto& future : futures) {
Juhyung Parkee293ba2024-07-09 23:46:20 +0900235 if (!future.first.get()) {
236 ret = false;
237 LOG(ERROR) << "Extraction of partition " << future.second << " failed";
Juhyung Parkc8c00572024-07-09 22:47:09 +0900238 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800239 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800240 }
Juhyung Parkee293ba2024-07-09 23:46:20 +0900241 return ret;
Kelvin Zhang596a3202022-03-07 14:13:42 -0800242}
243
244} // namespace chromeos_update_engine
245
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700246namespace {
247
248bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
249 for (const auto& part : manifest.partitions()) {
250 if (part.has_old_partition_info()) {
251 return true;
252 }
253 }
254 return false;
255}
256
257} // namespace
258
Kelvin Zhang596a3202022-03-07 14:13:42 -0800259int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700260 gflags::SetUsageMessage(
261 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800262 gflags::ParseCommandLineFlags(&argc, &argv, true);
263 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700264 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
265 const std::set<std::string> partitions(
266 std::make_move_iterator(tokens.begin()),
267 std::make_move_iterator(tokens.end()));
268 if (FLAGS_payload.empty()) {
269 LOG(ERROR) << "--payload <payload path> is required";
270 return 1;
271 }
272 if (!partitions.empty()) {
273 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
274 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800275 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
276 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700277 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800278 return 1;
279 }
280 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
281 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
282 if (payload_size <= 0) {
283 PLOG(ERROR)
284 << "Couldn't determine size of payload file, or payload file is empty";
285 return 1;
286 }
287
288 PayloadMetadata payload_metadata;
289 auto payload = static_cast<unsigned char*>(
290 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
291
292 if (payload == MAP_FAILED) {
293 PLOG(ERROR) << "Failed to mmap() payload file";
294 return 1;
295 }
296
297 auto munmap_deleter = [payload_size](auto payload) {
298 munmap(payload, payload_size);
299 };
300 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
301 payload, munmap_deleter};
302 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
303 payload_size - FLAGS_payload_offset,
304 nullptr) !=
305 chromeos_update_engine::MetadataParseResult::kSuccess) {
306 LOG(ERROR) << "Payload header parse failed!";
307 return 1;
308 }
309 DeltaArchiveManifest manifest;
310 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
311 payload_size - FLAGS_payload_offset,
312 &manifest)) {
313 LOG(ERROR) << "Failed to parse manifest!";
314 return 1;
315 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700316 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
317 LOG(ERROR) << FLAGS_payload
318 << " is an incremental OTA, --input_dir parameter is required.";
319 return 1;
320 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800321 return !ExtractImagesFromOTA(manifest,
322 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700323 payload_fd,
324 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700325 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700326 FLAGS_output_dir,
327 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800328}