blob: d3b270508ded005eb26e08bab1ef78c1c5cdec15 [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)),
137 HexEncode(op.src_sha256_hash()));
138 }
139
140 blob.resize(op.data_length());
141 const auto op_data_offset = data_begin + op.data_offset();
142 ssize_t bytes_read = 0;
143 TEST_AND_RETURN_FALSE(utils::PReadAll(
144 payload_fd, blob.data(), blob.size(), op_data_offset, &bytes_read));
145 if (op.has_data_sha256_hash()) {
146 brillo::Blob actual_hash;
147 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(blob, &actual_hash));
148 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
149 HexEncode(op.data_sha256_hash()));
150 }
151 auto direct_writer = std::make_unique<DirectExtentWriter>(out_fd);
152 if (op.type() == InstallOperation::ZERO) {
153 TEST_AND_RETURN_FALSE(
154 executor.ExecuteZeroOrDiscardOperation(op, std::move(direct_writer)));
155 } else if (op.type() == InstallOperation::REPLACE ||
156 op.type() == InstallOperation::REPLACE_BZ ||
157 op.type() == InstallOperation::REPLACE_XZ) {
158 TEST_AND_RETURN_FALSE(executor.ExecuteReplaceOperation(
159 op, std::move(direct_writer), blob.data()));
160 } else if (op.type() == InstallOperation::SOURCE_COPY) {
161 CHECK(in_fd->IsOpen());
162 TEST_AND_RETURN_FALSE(executor.ExecuteSourceCopyOperation(
163 op, std::move(direct_writer), in_fd));
164 } else {
165 CHECK(in_fd->IsOpen());
166 TEST_AND_RETURN_FALSE(executor.ExecuteDiffOperation(
167 op, std::move(direct_writer), in_fd, blob.data(), blob.size()));
168 }
169 }
170 WriteVerity(partition, out_fd, manifest.block_size());
171 int err =
172 truncate64(output_path.c_str(), partition.new_partition_info().size());
173 if (err) {
174 PLOG(ERROR) << "Failed to truncate " << output_path << " to "
175 << partition.new_partition_info().size();
176 }
177 brillo::Blob actual_hash;
178 TEST_AND_RETURN_FALSE(
179 HashCalculator::RawHashOfFile(output_path, &actual_hash));
180 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
181 HexEncode(partition.new_partition_info().hash()))
182 << " Partition " << partition.partition_name()
183 << " hash mismatches. Either the source image or OTA package is "
184 "corrupted.";
185
186 return true;
187}
188
Kelvin Zhang596a3202022-03-07 14:13:42 -0800189bool ExtractImagesFromOTA(const DeltaArchiveManifest& manifest,
190 const PayloadMetadata& metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700191 int payload_fd,
192 size_t payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700193 std::string_view input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700194 std::string_view output_dir,
195 const std::set<std::string>& partitions) {
Kelvin Zhangb9368922022-03-17 21:11:32 -0700196 const size_t data_begin = metadata.GetMetadataSize() +
197 metadata.GetMetadataSignatureSize() +
198 payload_offset;
Juhyung Park202dee22024-07-09 22:39:11 +0900199
Juhyung Parkc8c00572024-07-09 22:47:09 +0900200 if (FLAGS_single_thread) {
201 for (const auto& partition : manifest.partitions()) {
202 if (!ExtractImageFromPartition(manifest,
203 partition,
204 data_begin,
205 payload_fd,
206 input_dir,
207 output_dir)) {
208 return false;
209 }
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700210 }
Juhyung Parkc8c00572024-07-09 22:47:09 +0900211 } else {
212 std::vector<std::future<bool>> futures;
213 for (const auto& partition : manifest.partitions()) {
214 futures.push_back(std::async(std::launch::async,
215 ExtractImageFromPartition,
216 manifest,
Juhyung Park202dee22024-07-09 22:39:11 +0900217 partition,
218 data_begin,
219 payload_fd,
220 input_dir,
Juhyung Parkc8c00572024-07-09 22:47:09 +0900221 output_dir));
222 }
223 for (auto& future : futures) {
224 if (!future.get()) {
225 return false;
226 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800227 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800228 }
229 return true;
230}
231
232} // namespace chromeos_update_engine
233
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700234namespace {
235
236bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
237 for (const auto& part : manifest.partitions()) {
238 if (part.has_old_partition_info()) {
239 return true;
240 }
241 }
242 return false;
243}
244
245} // namespace
246
Kelvin Zhang596a3202022-03-07 14:13:42 -0800247int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700248 gflags::SetUsageMessage(
249 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800250 gflags::ParseCommandLineFlags(&argc, &argv, true);
251 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700252 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
253 const std::set<std::string> partitions(
254 std::make_move_iterator(tokens.begin()),
255 std::make_move_iterator(tokens.end()));
256 if (FLAGS_payload.empty()) {
257 LOG(ERROR) << "--payload <payload path> is required";
258 return 1;
259 }
260 if (!partitions.empty()) {
261 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
262 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800263 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
264 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700265 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800266 return 1;
267 }
268 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
269 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
270 if (payload_size <= 0) {
271 PLOG(ERROR)
272 << "Couldn't determine size of payload file, or payload file is empty";
273 return 1;
274 }
275
276 PayloadMetadata payload_metadata;
277 auto payload = static_cast<unsigned char*>(
278 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
279
280 if (payload == MAP_FAILED) {
281 PLOG(ERROR) << "Failed to mmap() payload file";
282 return 1;
283 }
284
285 auto munmap_deleter = [payload_size](auto payload) {
286 munmap(payload, payload_size);
287 };
288 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
289 payload, munmap_deleter};
290 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
291 payload_size - FLAGS_payload_offset,
292 nullptr) !=
293 chromeos_update_engine::MetadataParseResult::kSuccess) {
294 LOG(ERROR) << "Payload header parse failed!";
295 return 1;
296 }
297 DeltaArchiveManifest manifest;
298 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
299 payload_size - FLAGS_payload_offset,
300 &manifest)) {
301 LOG(ERROR) << "Failed to parse manifest!";
302 return 1;
303 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700304 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
305 LOG(ERROR) << FLAGS_payload
306 << " is an incremental OTA, --input_dir parameter is required.";
307 return 1;
308 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800309 return !ExtractImagesFromOTA(manifest,
310 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700311 payload_fd,
312 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700313 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700314 FLAGS_output_dir,
315 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800316}