blob: a61a430a1d315e5122e887afde879787a18a348f [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
Juhyung Park202dee22024-07-09 22:39:11 +090096bool ExtractImageFromPartition(const DeltaArchiveManifest& manifest,
97 const PartitionUpdate& partition,
98 const size_t data_begin,
99 int payload_fd,
100 std::string_view input_dir,
101 std::string_view output_dir) {
102 InstallOperationExecutor executor(manifest.block_size());
103 const base::FilePath output_dir_path(
104 base::StringPiece(output_dir.data(), output_dir.size()));
105 const base::FilePath input_dir_path(
106 base::StringPiece(input_dir.data(), input_dir.size()));
107 std::vector<unsigned char> blob;
108
109 LOG(INFO) << "Extracting partition " << partition.partition_name()
110 << " size: " << partition.new_partition_info().size();
111 const auto output_path =
112 output_dir_path.Append(partition.partition_name() + ".img").value();
113 auto out_fd =
114 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
115 TEST_AND_RETURN_FALSE_ERRNO(
116 out_fd->Open(output_path.c_str(), O_RDWR | O_CREAT, 0644));
117 auto in_fd =
118 std::make_shared<chromeos_update_engine::EintrSafeFileDescriptor>();
119 if (partition.has_old_partition_info()) {
120 const auto input_path =
121 input_dir_path.Append(partition.partition_name() + ".img").value();
122 LOG(INFO) << "Incremental OTA detected for partition "
123 << partition.partition_name() << " opening source image "
124 << input_path;
125 CHECK(in_fd->Open(input_path.c_str(), O_RDONLY))
126 << " failed to open " << input_path;
127 }
128
129 for (const auto& op : partition.operations()) {
130 if (op.has_src_sha256_hash()) {
131 brillo::Blob actual_hash;
132 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
133 in_fd, op.src_extents(), manifest.block_size(), &actual_hash));
134 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
135 HexEncode(op.src_sha256_hash()));
136 }
137
138 blob.resize(op.data_length());
139 const auto op_data_offset = data_begin + op.data_offset();
140 ssize_t bytes_read = 0;
141 TEST_AND_RETURN_FALSE(utils::PReadAll(
142 payload_fd, blob.data(), blob.size(), op_data_offset, &bytes_read));
143 if (op.has_data_sha256_hash()) {
144 brillo::Blob actual_hash;
145 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(blob, &actual_hash));
146 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
147 HexEncode(op.data_sha256_hash()));
148 }
149 auto direct_writer = std::make_unique<DirectExtentWriter>(out_fd);
150 if (op.type() == InstallOperation::ZERO) {
151 TEST_AND_RETURN_FALSE(
152 executor.ExecuteZeroOrDiscardOperation(op, std::move(direct_writer)));
153 } else if (op.type() == InstallOperation::REPLACE ||
154 op.type() == InstallOperation::REPLACE_BZ ||
155 op.type() == InstallOperation::REPLACE_XZ) {
156 TEST_AND_RETURN_FALSE(executor.ExecuteReplaceOperation(
157 op, std::move(direct_writer), blob.data()));
158 } else if (op.type() == InstallOperation::SOURCE_COPY) {
159 CHECK(in_fd->IsOpen());
160 TEST_AND_RETURN_FALSE(executor.ExecuteSourceCopyOperation(
161 op, std::move(direct_writer), in_fd));
162 } else {
163 CHECK(in_fd->IsOpen());
164 TEST_AND_RETURN_FALSE(executor.ExecuteDiffOperation(
165 op, std::move(direct_writer), in_fd, blob.data(), blob.size()));
166 }
167 }
168 WriteVerity(partition, out_fd, manifest.block_size());
169 int err =
170 truncate64(output_path.c_str(), partition.new_partition_info().size());
171 if (err) {
172 PLOG(ERROR) << "Failed to truncate " << output_path << " to "
173 << partition.new_partition_info().size();
174 }
175 brillo::Blob actual_hash;
176 TEST_AND_RETURN_FALSE(
177 HashCalculator::RawHashOfFile(output_path, &actual_hash));
178 CHECK_EQ(HexEncode(ToStringView(actual_hash)),
179 HexEncode(partition.new_partition_info().hash()))
180 << " Partition " << partition.partition_name()
181 << " hash mismatches. Either the source image or OTA package is "
182 "corrupted.";
183
184 return true;
185}
186
Kelvin Zhang596a3202022-03-07 14:13:42 -0800187bool ExtractImagesFromOTA(const DeltaArchiveManifest& manifest,
188 const PayloadMetadata& metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700189 int payload_fd,
190 size_t payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700191 std::string_view input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700192 std::string_view output_dir,
193 const std::set<std::string>& partitions) {
Kelvin Zhangb9368922022-03-17 21:11:32 -0700194 const size_t data_begin = metadata.GetMetadataSize() +
195 metadata.GetMetadataSignatureSize() +
196 payload_offset;
Juhyung Park202dee22024-07-09 22:39:11 +0900197
Kelvin Zhang596a3202022-03-07 14:13:42 -0800198 for (const auto& partition : manifest.partitions()) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700199 if (!partitions.empty() &&
200 partitions.count(partition.partition_name()) == 0) {
201 continue;
202 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700203
Juhyung Park202dee22024-07-09 22:39:11 +0900204 if (!ExtractImageFromPartition(manifest,
205 partition,
206 data_begin,
207 payload_fd,
208 input_dir,
209 output_dir)) {
210 return false;
Kelvin Zhang596a3202022-03-07 14:13:42 -0800211 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800212 }
213 return true;
214}
215
216} // namespace chromeos_update_engine
217
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700218namespace {
219
220bool IsIncrementalOTA(const DeltaArchiveManifest& manifest) {
221 for (const auto& part : manifest.partitions()) {
222 if (part.has_old_partition_info()) {
223 return true;
224 }
225 }
226 return false;
227}
228
229} // namespace
230
Kelvin Zhang596a3202022-03-07 14:13:42 -0800231int main(int argc, char* argv[]) {
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700232 gflags::SetUsageMessage(
233 "A tool to extract device images from Android OTA packages");
Kelvin Zhang596a3202022-03-07 14:13:42 -0800234 gflags::ParseCommandLineFlags(&argc, &argv, true);
235 xz_crc32_init();
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700236 auto tokens = android::base::Tokenize(FLAGS_partitions, ",");
237 const std::set<std::string> partitions(
238 std::make_move_iterator(tokens.begin()),
239 std::make_move_iterator(tokens.end()));
240 if (FLAGS_payload.empty()) {
241 LOG(ERROR) << "--payload <payload path> is required";
242 return 1;
243 }
244 if (!partitions.empty()) {
245 LOG(INFO) << "Extracting " << android::base::Join(partitions, ", ");
246 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800247 int payload_fd = open(FLAGS_payload.c_str(), O_RDONLY | O_CLOEXEC);
248 if (payload_fd < 0) {
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700249 PLOG(ERROR) << "Failed to open payload file";
Kelvin Zhang596a3202022-03-07 14:13:42 -0800250 return 1;
251 }
252 chromeos_update_engine::ScopedFdCloser closer{&payload_fd};
253 auto payload_size = chromeos_update_engine::utils::FileSize(payload_fd);
254 if (payload_size <= 0) {
255 PLOG(ERROR)
256 << "Couldn't determine size of payload file, or payload file is empty";
257 return 1;
258 }
259
260 PayloadMetadata payload_metadata;
261 auto payload = static_cast<unsigned char*>(
262 mmap(nullptr, payload_size, PROT_READ, MAP_PRIVATE, payload_fd, 0));
263
264 if (payload == MAP_FAILED) {
265 PLOG(ERROR) << "Failed to mmap() payload file";
266 return 1;
267 }
268
269 auto munmap_deleter = [payload_size](auto payload) {
270 munmap(payload, payload_size);
271 };
272 std::unique_ptr<unsigned char, decltype(munmap_deleter)> munmapper{
273 payload, munmap_deleter};
274 if (payload_metadata.ParsePayloadHeader(payload + FLAGS_payload_offset,
275 payload_size - FLAGS_payload_offset,
276 nullptr) !=
277 chromeos_update_engine::MetadataParseResult::kSuccess) {
278 LOG(ERROR) << "Payload header parse failed!";
279 return 1;
280 }
281 DeltaArchiveManifest manifest;
282 if (!payload_metadata.GetManifest(payload + FLAGS_payload_offset,
283 payload_size - FLAGS_payload_offset,
284 &manifest)) {
285 LOG(ERROR) << "Failed to parse manifest!";
286 return 1;
287 }
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700288 if (IsIncrementalOTA(manifest) && FLAGS_input_dir.empty()) {
289 LOG(ERROR) << FLAGS_payload
290 << " is an incremental OTA, --input_dir parameter is required.";
291 return 1;
292 }
Kelvin Zhang596a3202022-03-07 14:13:42 -0800293 return !ExtractImagesFromOTA(manifest,
294 payload_metadata,
Kelvin Zhangb9368922022-03-17 21:11:32 -0700295 payload_fd,
296 FLAGS_payload_offset,
Kelvin Zhang91e839c2022-04-05 14:25:00 -0700297 FLAGS_input_dir,
Kelvin Zhangc7515d42022-03-23 10:44:16 -0700298 FLAGS_output_dir,
299 partitions);
Kelvin Zhang596a3202022-03-07 14:13:42 -0800300}