blob: 713cfc35f77dc26e83ec11ee43836dbd30cf4120 [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>
Kelvin Zhangc7515d42022-03-23 10:44:16 -070020#include <iterator>
Kelvin Zhang596a3202022-03-07 14:13:42 -080021#include <memory>
22
Kelvin Zhang91e839c2022-04-05 14:25:00 -070023#include <fcntl.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080024#include <sys/mman.h>
25#include <sys/stat.h>
26
Kelvin Zhangc7515d42022-03-23 10:44:16 -070027#include <android-base/strings.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080028#include <base/files/file_path.h>
29#include <gflags/gflags.h>
30#include <unistd.h>
Kelvin Zhang91e839c2022-04-05 14:25:00 -070031#include <xz.h>
Kelvin Zhang596a3202022-03-07 14:13:42 -080032
33#include "update_engine/common/utils.h"
34#include "update_engine/common/hash_calculator.h"
35#include "update_engine/payload_consumer/file_descriptor.h"
Kelvin Zhang91e839c2022-04-05 14:25:00 -070036#include "update_engine/payload_consumer/file_descriptor_utils.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080037#include "update_engine/payload_consumer/install_operation_executor.h"
38#include "update_engine/payload_consumer/payload_metadata.h"
Kelvin Zhang91e839c2022-04-05 14:25:00 -070039#include "update_engine/payload_consumer/verity_writer_android.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080040#include "update_engine/update_metadata.pb.h"
Kelvin Zhang596a3202022-03-07 14:13:42 -080041
42DEFINE_string(payload, "", "Path to payload.bin");
Kelvin Zhang91e839c2022-04-05 14:25:00 -070043DEFINE_string(
44 input_dir,
45 "",
46 "Directory to read input images. Only required for incremental OTAs");
Kelvin Zhang596a3202022-03-07 14:13:42 -080047DEFINE_string(output_dir, "", "Directory to put output images");
48DEFINE_int64(payload_offset,
49 0,
50 "Offset to start of payload.bin. Useful if payload path actually "
51 "points to a .zip file containing payload.bin");
Kelvin Zhangc7515d42022-03-23 10:44:16 -070052DEFINE_string(partitions,
53 "",
54 "Comma separated list of partitions to extract, leave empty for "
55 "extracting all partitions");
Kelvin Zhang596a3202022-03-07 14:13:42 -080056
57using chromeos_update_engine::DeltaArchiveManifest;
58using chromeos_update_engine::PayloadMetadata;
59
60namespace chromeos_update_engine {
61
Kelvin Zhang91e839c2022-04-05 14:25:00 -070062void WriteVerity(const PartitionUpdate& partition,
63 FileDescriptorPtr fd,
64 const size_t block_size) {
65 // 512KB buffer, arbitrary value. Larger buffers may improve performance.
66 static constexpr size_t BUFFER_SIZE = 1024 * 512;
67 if (partition.hash_tree_extent().num_blocks() == 0 &&
68 partition.fec_extent().num_blocks() == 0) {
69 return;
70 }
71 InstallPlan::Partition install_part;
72 install_part.block_size = block_size;
73 CHECK(install_part.ParseVerityConfig(partition));
74 VerityWriterAndroid writer;
75 CHECK(writer.Init(install_part));
76 std::array<uint8_t, BUFFER_SIZE> buffer;
77 const auto data_size =
78 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
79 size_t offset = 0;
80 while (offset < data_size) {
81 const auto bytes_to_read =
82 static_cast<ssize_t>(std::min(BUFFER_SIZE, data_size - offset));
83 ssize_t bytes_read;
84 CHECK(
85 utils::ReadAll(fd, buffer.data(), bytes_to_read, offset, &bytes_read));
86 CHECK_EQ(bytes_read, bytes_to_read)
87 << " Failed to read at offset " << offset << " "
88 << android::base::ErrnoNumberAsString(errno);
89 writer.Update(offset, buffer.data(), bytes_read);
90 offset += bytes_read;
91 }
92 CHECK(writer.Finalize(fd.get(), fd.get()));
93 return;
94}
95
Kelvin Zhang596a3202022-03-07 14:13:42 -080096bool ExtractImagesFromOTA(const DeltaArchiveManifest& manifest,
97 const PayloadMetadata& metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -070098 int payload_fd,
99 size_t payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700100 std::string_view input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700101 std::string_view output_dir,
102 const std::set<std::string>& partitions) {
Kelvin Zhang596a3202022-03-07 14:13:42 -0800103 InstallOperationExecutor executor(manifest.block_size());
Kelvin Zhangb9368922022-03-17 21:11:32 -0700104 const size_t data_begin = metadata.GetMetadataSize() +
105 metadata.GetMetadataSignatureSize() +
106 payload_offset;
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700107 const base::FilePath output_dir_path(
Kelvin Zhang596a3202022-03-07 14:13:42 -0800108 base::StringPiece(output_dir.data(), output_dir.size()));
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700109 const base::FilePath input_dir_path(
110 base::StringPiece(input_dir.data(), input_dir.size()));
Kelvin Zhangb9368922022-03-17 21:11:32 -0700111 std::vector<unsigned char> blob;
Kelvin Zhang596a3202022-03-07 14:13:42 -0800112 for (const auto& partition : manifest.partitions()) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700113 if (!partitions.empty() &&
114 partitions.count(partition.partition_name()) == 0) {
115 continue;
116 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800117 LOG(INFO) << "Extracting partition " << partition.partition_name()
118 << " size: " << partition.new_partition_info().size();
119 const auto output_path =
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700120 output_dir_path.Append(partition.partition_name() + ".img").value();
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700121 auto out_fd =
Kelvin Zhang596a3202022-03-07 14:13:42 -0800122 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
123 TEST_AND_RETURN_FALSE_ERRNO(
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700124 out_fd->Open(output_path.c_str(), O_RDWR | O_CREAT, 0644));
125 auto in_fd =
126 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
Kelvin Zhang93e38102022-04-15 11:11:57 -0700127 if (partition.has_old_partition_info()) {
128 const auto input_path =
129 input_dir_path.Append(partition.partition_name() + ".img").value();
130 LOG(INFO) << "Incremental OTA detected for partition "
131 << partition.partition_name() << " opening source image "
132 << input_path;
133 CHECK(in_fd->Open(input_path.c_str(), O_RDONLY))
134 << " failed to open " << input_path;
135 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700136
Kelvin Zhang596a3202022-03-07 14:13:42 -0800137 for (const auto& op : partition.operations()) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700138 if (op.has_src_sha256_hash()) {
139 brillo::Blob actual_hash;
140 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
141 in_fd, op.src_extents(), manifest.block_size(), &actual_hash));
142 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
143 HexEncode(op.src_sha256_hash()));
144 }
145
Kelvin Zhangb9368922022-03-17 21:11:32 -0700146 blob.resize(op.data_length());
147 const auto op_data_offset = data_begin + op.data_offset();
148 ssize_t bytes_read = 0;
149 TEST_AND_RETURN_FALSE(utils::PReadAll(
150 payload_fd, blob.data(), blob.size(), op_data_offset, &bytes_read));
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700151 if (op.has_data_sha256_hash()) {
152 brillo::Blob actual_hash;
153 TEST_AND_RETURN_FALSE(
154 HashCalculator::RawHashOfData(blob, &actual_hash));
155 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
156 HexEncode(op.data_sha256_hash()));
157 }
158 auto direct_writer = std::make_unique<DirectExtentWriter>(out_fd);
Kelvin Zhangcf323872022-03-25 14:00:39 -0700159 if (op.type() == InstallOperation::ZERO) {
160 TEST_AND_RETURN_FALSE(executor.ExecuteZeroOrDiscardOperation(
161 op, std::move(direct_writer)));
162 } else if (op.type() == InstallOperation::REPLACE ||
163 op.type() == InstallOperation::REPLACE_BZ ||
164 op.type() == InstallOperation::REPLACE_XZ) {
165 TEST_AND_RETURN_FALSE(executor.ExecuteReplaceOperation(
Daniel Zheng17be0f92024-01-23 15:12:33 -0800166 op, std::move(direct_writer), blob.data()));
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700167 } else if (op.type() == InstallOperation::SOURCE_COPY) {
Kelvin Zhang93e38102022-04-15 11:11:57 -0700168 CHECK(in_fd->IsOpen());
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700169 TEST_AND_RETURN_FALSE(executor.ExecuteSourceCopyOperation(
170 op, std::move(direct_writer), in_fd));
Kelvin Zhangcf323872022-03-25 14:00:39 -0700171 } else {
Kelvin Zhang93e38102022-04-15 11:11:57 -0700172 CHECK(in_fd->IsOpen());
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700173 TEST_AND_RETURN_FALSE(executor.ExecuteDiffOperation(
174 op, std::move(direct_writer), in_fd, blob.data(), blob.size()));
Kelvin Zhangcf323872022-03-25 14:00:39 -0700175 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800176 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700177 WriteVerity(partition, out_fd, manifest.block_size());
Kelvin Zhang596a3202022-03-07 14:13:42 -0800178 int err =
179 truncate64(output_path.c_str(), partition.new_partition_info().size());
180 if (err) {
181 PLOG(ERROR) << "Failed to truncate " << output_path << " to "
182 << partition.new_partition_info().size();
183 }
184 brillo::Blob actual_hash;
185 TEST_AND_RETURN_FALSE(
186 HashCalculator::RawHashOfFile(output_path, &actual_hash));
187 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700188 HexEncode(partition.new_partition_info().hash()))
189 << " Partition " << partition.partition_name()
190 << " hash mismatches. Either the source image or OTA package is "
191 "corrupted.";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800192 }
193 return true;
194}
195
196} // namespace chromeos_update_engine
197
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700198namespace {
199
200bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
201 for (const auto& part : manifest.partitions()) {
202 if (part.has_old_partition_info()) {
203 return true;
204 }
205 }
206 return false;
207}
208
209} // namespace
210
Kelvin Zhang596a3202022-03-07 14:13:42 -0800211int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700212 gflags::SetUsageMessage(
213 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800214 gflags::ParseCommandLineFlags(&argc, &argv, true);
215 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700216 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
217 const std::set<std::string> partitions(
218 std::make_move_iterator(tokens.begin()),
219 std::make_move_iterator(tokens.end()));
220 if (FLAGS_payload.empty()) {
221 LOG(ERROR) << "--payload <payload path> is required";
222 return 1;
223 }
224 if (!partitions.empty()) {
225 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
226 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800227 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
228 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700229 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800230 return 1;
231 }
232 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
233 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
234 if (payload_size <= 0) {
235 PLOG(ERROR)
236 << "Couldn't determine size of payload file, or payload file is empty";
237 return 1;
238 }
239
240 PayloadMetadata payload_metadata;
241 auto payload = static_cast<unsigned char*>(
242 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
243
244 if (payload == MAP_FAILED) {
245 PLOG(ERROR) << "Failed to mmap() payload file";
246 return 1;
247 }
248
249 auto munmap_deleter = [payload_size](auto payload) {
250 munmap(payload, payload_size);
251 };
252 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
253 payload, munmap_deleter};
254 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
255 payload_size - FLAGS_payload_offset,
256 nullptr) !=
257 chromeos_update_engine::MetadataParseResult::kSuccess) {
258 LOG(ERROR) << "Payload header parse failed!";
259 return 1;
260 }
261 DeltaArchiveManifest manifest;
262 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
263 payload_size - FLAGS_payload_offset,
264 &manifest)) {
265 LOG(ERROR) << "Failed to parse manifest!";
266 return 1;
267 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700268 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
269 LOG(ERROR) << FLAGS_payload
270 << " is an incremental OTA, --input_dir parameter is required.";
271 return 1;
272 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800273 return !ExtractImagesFromOTA(manifest,
274 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700275 payload_fd,
276 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700277 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700278 FLAGS_output_dir,
279 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800280}