blob: 7492bc5aa5548d4831c0c2069d36b7631ffb9ac9 [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();
121 const auto input_path =
122 input_dir_path.Append(partition.partition_name() + ".img").value();
123 auto out_fd =
Kelvin Zhang596a3202022-03-07 14:13:42 -0800124 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
125 TEST_AND_RETURN_FALSE_ERRNO(
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700126 out_fd->Open(output_path.c_str(), O_RDWR | O_CREAT, 0644));
127 auto in_fd =
128 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
129 TEST_AND_RETURN_FALSE_ERRNO(in_fd->Open(input_path.c_str(), O_RDONLY));
130
Kelvin Zhang596a3202022-03-07 14:13:42 -0800131 for (const auto& op : partition.operations()) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700132 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
Kelvin Zhangb9368922022-03-17 21:11:32 -0700140 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));
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700145 if (op.has_data_sha256_hash()) {
146 brillo::Blob actual_hash;
147 TEST_AND_RETURN_FALSE(
148 HashCalculator::RawHashOfData(blob, &actual_hash));
149 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
150 HexEncode(op.data_sha256_hash()));
151 }
152 auto direct_writer = std::make_unique<DirectExtentWriter>(out_fd);
Kelvin Zhangcf323872022-03-25 14:00:39 -0700153 if (op.type() == InstallOperation::ZERO) {
154 TEST_AND_RETURN_FALSE(executor.ExecuteZeroOrDiscardOperation(
155 op, std::move(direct_writer)));
156 } else if (op.type() == InstallOperation::REPLACE ||
157 op.type() == InstallOperation::REPLACE_BZ ||
158 op.type() == InstallOperation::REPLACE_XZ) {
159 TEST_AND_RETURN_FALSE(executor.ExecuteReplaceOperation(
160 op, std::move(direct_writer), blob.data(), blob.size()));
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700161 } else if (op.type() == InstallOperation::SOURCE_COPY) {
162 TEST_AND_RETURN_FALSE(executor.ExecuteSourceCopyOperation(
163 op, std::move(direct_writer), in_fd));
Kelvin Zhangcf323872022-03-25 14:00:39 -0700164 } else {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700165 TEST_AND_RETURN_FALSE(executor.ExecuteDiffOperation(
166 op, std::move(direct_writer), in_fd, blob.data(), blob.size()));
Kelvin Zhangcf323872022-03-25 14:00:39 -0700167 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800168 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700169 WriteVerity(partition, out_fd, manifest.block_size());
Kelvin Zhang596a3202022-03-07 14:13:42 -0800170 int err =
171 truncate64(output_path.c_str(), partition.new_partition_info().size());
172 if (err) {
173 PLOG(ERROR) << "Failed to truncate " << output_path << " to "
174 << partition.new_partition_info().size();
175 }
176 brillo::Blob actual_hash;
177 TEST_AND_RETURN_FALSE(
178 HashCalculator::RawHashOfFile(output_path, &actual_hash));
179 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700180 HexEncode(partition.new_partition_info().hash()))
181 << " Partition " << partition.partition_name()
182 << " hash mismatches. Either the source image or OTA package is "
183 "corrupted.";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800184 }
185 return true;
186}
187
188} // namespace chromeos_update_engine
189
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700190namespace {
191
192bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
193 for (const auto& part : manifest.partitions()) {
194 if (part.has_old_partition_info()) {
195 return true;
196 }
197 }
198 return false;
199}
200
201} // namespace
202
Kelvin Zhang596a3202022-03-07 14:13:42 -0800203int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700204 gflags::SetUsageMessage(
205 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800206 gflags::ParseCommandLineFlags(&argc, &argv, true);
207 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700208 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
209 const std::set<std::string> partitions(
210 std::make_move_iterator(tokens.begin()),
211 std::make_move_iterator(tokens.end()));
212 if (FLAGS_payload.empty()) {
213 LOG(ERROR) << "--payload <payload path> is required";
214 return 1;
215 }
216 if (!partitions.empty()) {
217 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
218 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800219 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
220 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700221 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800222 return 1;
223 }
224 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
225 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
226 if (payload_size <= 0) {
227 PLOG(ERROR)
228 << "Couldn't determine size of payload file, or payload file is empty";
229 return 1;
230 }
231
232 PayloadMetadata payload_metadata;
233 auto payload = static_cast<unsigned char*>(
234 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
235
236 if (payload == MAP_FAILED) {
237 PLOG(ERROR) << "Failed to mmap() payload file";
238 return 1;
239 }
240
241 auto munmap_deleter = [payload_size](auto payload) {
242 munmap(payload, payload_size);
243 };
244 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
245 payload, munmap_deleter};
246 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
247 payload_size - FLAGS_payload_offset,
248 nullptr) !=
249 chromeos_update_engine::MetadataParseResult::kSuccess) {
250 LOG(ERROR) << "Payload header parse failed!";
251 return 1;
252 }
253 DeltaArchiveManifest manifest;
254 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
255 payload_size - FLAGS_payload_offset,
256 &manifest)) {
257 LOG(ERROR) << "Failed to parse manifest!";
258 return 1;
259 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700260 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
261 LOG(ERROR) << FLAGS_payload
262 << " is an incremental OTA, --input_dir parameter is required.";
263 return 1;
264 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800265 return !ExtractImagesFromOTA(manifest,
266 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700267 payload_fd,
268 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700269 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700270 FLAGS_output_dir,
271 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800272}