blob: ccd68dc3e533a226b9577add16a5f1ddd71c72e7 [file] [log] [blame]
Doug Zongker512536a2010-02-17 16:11:44 -08001/*
2 * Copyright (C) 2009 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
17/*
Tianjie Xu82582b42017-08-31 18:05:19 -070018 * This program constructs binary patches for images -- such as boot.img and recovery.img -- that
19 * consist primarily of large chunks of gzipped data interspersed with uncompressed data. Doing a
20 * naive bsdiff of these files is not useful because small changes in the data lead to large
21 * changes in the compressed bitstream; bsdiff patches of gzipped data are typically as large as
22 * the data itself.
Doug Zongker512536a2010-02-17 16:11:44 -080023 *
Tianjie Xu82582b42017-08-31 18:05:19 -070024 * To patch these usefully, we break the source and target images up into chunks of two types:
25 * "normal" and "gzip". Normal chunks are simply patched using a plain bsdiff. Gzip chunks are
26 * first expanded, then a bsdiff is applied to the uncompressed data, then the patched data is
27 * gzipped using the same encoder parameters. Patched chunks are concatenated together to create
28 * the output file; the output image should be *exactly* the same series of bytes as the target
29 * image used originally to generate the patch.
Doug Zongker512536a2010-02-17 16:11:44 -080030 *
Tianjie Xu82582b42017-08-31 18:05:19 -070031 * To work well with this tool, the gzipped sections of the target image must have been generated
32 * using the same deflate encoder that is available in applypatch, namely, the one in the zlib
33 * library. In practice this means that images should be compressed using the "minigzip" tool
34 * included in the zlib distribution, not the GNU gzip program.
Doug Zongker512536a2010-02-17 16:11:44 -080035 *
Tianjie Xu82582b42017-08-31 18:05:19 -070036 * An "imgdiff" patch consists of a header describing the chunk structure of the file and any
37 * encoding parameters needed for the gzipped chunks, followed by N bsdiff patches, one per chunk.
Doug Zongker512536a2010-02-17 16:11:44 -080038 *
Tianjie Xu82582b42017-08-31 18:05:19 -070039 * For a diff to be generated, the source and target must be in well-formed zip archive format;
40 * or they are image files with the same "chunk" structure: that is, the same number of gzipped and
41 * normal chunks in the same order. Android boot and recovery images currently consist of five
42 * chunks: a small normal header, a gzipped kernel, a small normal section, a gzipped ramdisk, and
43 * finally a small normal footer.
Doug Zongker512536a2010-02-17 16:11:44 -080044 *
Tianjie Xu82582b42017-08-31 18:05:19 -070045 * Caveats: we locate gzipped sections within the source and target images by searching for the
46 * byte sequence 1f8b0800: 1f8b is the gzip magic number; 08 specifies the "deflate" encoding
47 * [the only encoding supported by the gzip standard]; and 00 is the flags byte. We do not
48 * currently support any extra header fields (which would be indicated by a nonzero flags byte).
49 * We also don't handle the case when that byte sequence appears spuriously in the file. (Note
50 * that it would have to occur spuriously within a normal chunk to be a problem.)
Doug Zongker512536a2010-02-17 16:11:44 -080051 *
52 *
53 * The imgdiff patch header looks like this:
54 *
Tianjie Xu82582b42017-08-31 18:05:19 -070055 * "IMGDIFF2" (8) [magic number and version]
Doug Zongker512536a2010-02-17 16:11:44 -080056 * chunk count (4)
57 * for each chunk:
58 * chunk type (4) [CHUNK_{NORMAL, GZIP, DEFLATE, RAW}]
59 * if chunk type == CHUNK_NORMAL:
60 * source start (8)
61 * source len (8)
62 * bsdiff patch offset (8) [from start of patch file]
63 * if chunk type == CHUNK_GZIP: (version 1 only)
64 * source start (8)
65 * source len (8)
66 * bsdiff patch offset (8) [from start of patch file]
67 * source expanded len (8) [size of uncompressed source]
68 * target expected len (8) [size of uncompressed target]
69 * gzip level (4)
70 * method (4)
71 * windowBits (4)
72 * memLevel (4)
73 * strategy (4)
74 * gzip header len (4)
75 * gzip header (gzip header len)
76 * gzip footer (8)
77 * if chunk type == CHUNK_DEFLATE: (version 2 only)
78 * source start (8)
79 * source len (8)
80 * bsdiff patch offset (8) [from start of patch file]
81 * source expanded len (8) [size of uncompressed source]
82 * target expected len (8) [size of uncompressed target]
83 * gzip level (4)
84 * method (4)
85 * windowBits (4)
86 * memLevel (4)
87 * strategy (4)
88 * if chunk type == RAW: (version 2 only)
89 * target len (4)
90 * data (target len)
91 *
Tianjie Xu82582b42017-08-31 18:05:19 -070092 * All integers are little-endian. "source start" and "source len" specify the section of the
93 * input image that comprises this chunk, including the gzip header and footer for gzip chunks.
94 * "source expanded len" is the size of the uncompressed source data. "target expected len" is the
95 * size of the uncompressed data after applying the bsdiff patch. The next five parameters
96 * specify the zlib parameters to be used when compressing the patched data, and the next three
97 * specify the header and footer to be wrapped around the compressed data to create the output
98 * chunk (so that header contents like the timestamp are recreated exactly).
Doug Zongker512536a2010-02-17 16:11:44 -080099 *
Tianjie Xu82582b42017-08-31 18:05:19 -0700100 * After the header there are 'chunk count' bsdiff patches; the offset of each from the beginning
101 * of the file is specified in the header.
Doug Zongkera3ccba62012-08-20 15:28:02 -0700102 *
Tianjie Xu82582b42017-08-31 18:05:19 -0700103 * This tool can take an optional file of "bonus data". This is an extra file of data that is
104 * appended to chunk #1 after it is compressed (it must be a CHUNK_DEFLATE chunk). The same file
105 * must be available (and passed to applypatch with -b) when applying the patch. This is used to
106 * reduce the size of recovery-from-boot patches by combining the boot image with recovery ramdisk
Doug Zongkera3ccba62012-08-20 15:28:02 -0700107 * information that is stored on the system partition.
Tianjie Xu82582b42017-08-31 18:05:19 -0700108 *
109 * When generating the patch between two zip files, this tool has an option "--block-limit" to
110 * split the large source/target files into several pair of pieces, with each piece has at most
111 * *limit* blocks. When this option is used, we also need to output the split info into the file
112 * path specified by "--split-info".
113 *
114 * Format of split info file:
115 * 2 [version of imgdiff]
116 * n [count of split pieces]
117 * <patch_size>, <tgt_size>, <src_range> [size and ranges for split piece#1]
118 * ...
119 * <patch_size>, <tgt_size>, <src_range> [size and ranges for split piece#n]
120 *
121 * To split a pair of large zip files, we walk through the chunks in target zip and search by its
122 * entry_name in the source zip. If the entry_name is non-empty and a matching entry in source
123 * is found, we'll add the source entry to the current split source image; otherwise we'll skip
124 * this chunk and later do bsdiff between all the skipped trunks and the whole split source image.
125 * We move on to the next pair of pieces if the size of the split source image reaches the block
126 * limit.
127 *
128 * After the split, the target pieces are continuous and block aligned, while the source pieces
129 * are mutually exclusive. Some of the source blocks may not be used if there's no matching
130 * entry_name in the target; as a result, they won't be included in any of these split source
131 * images. Then we will generate patches accordingly between each split image pairs; in particular,
132 * the unmatched trunks in the split target will diff against the entire split source image.
133 *
134 * For example:
135 * Input: [src_image, tgt_image]
136 * Split: [src-0, tgt-0; src-1, tgt-1, src-2, tgt-2]
137 * Diff: [ patch-0; patch-1; patch-2]
138 *
139 * Patch: [(src-0, patch-0) = tgt-0; (src-1, patch-1) = tgt-1; (src-2, patch-2) = tgt-2]
140 * Concatenate: [tgt-0 + tgt-1 + tgt-2 = tgt_image]
Doug Zongker512536a2010-02-17 16:11:44 -0800141 */
142
Tao Bao97555da2016-12-15 10:15:06 -0800143#include "applypatch/imgdiff.h"
144
Doug Zongker512536a2010-02-17 16:11:44 -0800145#include <errno.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800146#include <fcntl.h>
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700147#include <getopt.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800148#include <stdio.h>
149#include <stdlib.h>
150#include <string.h>
151#include <sys/stat.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800152#include <sys/types.h>
Tao Bao97555da2016-12-15 10:15:06 -0800153#include <unistd.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800154
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800155#include <algorithm>
156#include <string>
157#include <vector>
158
Tao Baod37ce8f2016-12-17 17:10:04 -0800159#include <android-base/file.h>
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800160#include <android-base/logging.h>
161#include <android-base/memory.h>
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700162#include <android-base/parseint.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800163#include <android-base/unique_fd.h>
Alex Deymofa188262017-10-10 17:56:17 +0200164#include <bsdiff/bsdiff.h>
Tianjie Xu57dd9612017-08-17 17:50:56 -0700165#include <ziparchive/zip_archive.h>
Tao Bao97555da2016-12-15 10:15:06 -0800166#include <zlib.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700167
Tianjie Xu57dd9612017-08-17 17:50:56 -0700168#include "applypatch/imgdiff_image.h"
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700169#include "rangeset.h"
Tianjie Xu57dd9612017-08-17 17:50:56 -0700170
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800171using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800172
Tianjie Xu82582b42017-08-31 18:05:19 -0700173static constexpr size_t VERSION = 2;
174
175// We assume the header "IMGDIFF#" is 8 bytes.
176static_assert(VERSION <= 9, "VERSION occupies more than one byte.");
177
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700178static constexpr size_t BLOCK_SIZE = 4096;
179static constexpr size_t BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800180
Tianjie Xu12b90552017-03-07 14:44:14 -0800181// If we use this function to write the offset and length (type size_t), their values should not
182// exceed 2^63; because the signed bit will be casted away.
183static inline bool Write8(int fd, int64_t value) {
184 return android::base::WriteFully(fd, &value, sizeof(int64_t));
185}
186
187// Similarly, the value should not exceed 2^31 if we are casting from size_t (e.g. target chunk
188// size).
189static inline bool Write4(int fd, int32_t value) {
190 return android::base::WriteFully(fd, &value, sizeof(int32_t));
191}
192
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700193// Trim the head or tail to align with the block size. Return false if the chunk has nothing left
194// after alignment.
195static bool AlignHead(size_t* start, size_t* length) {
196 size_t residual = (*start % BLOCK_SIZE == 0) ? 0 : BLOCK_SIZE - *start % BLOCK_SIZE;
197
198 if (*length <= residual) {
199 *length = 0;
200 return false;
201 }
202
203 // Trim the data in the beginning.
204 *start += residual;
205 *length -= residual;
206 return true;
207}
208
209static bool AlignTail(size_t* start, size_t* length) {
210 size_t residual = (*start + *length) % BLOCK_SIZE;
211 if (*length <= residual) {
212 *length = 0;
213 return false;
214 }
215
216 // Trim the data in the end.
217 *length -= residual;
218 return true;
219}
220
221// Remove the used blocks from the source chunk to make sure the source ranges are mutually
222// exclusive after split. Return false if we fail to get the non-overlapped ranges. In such
223// a case, we'll skip the entire source chunk.
224static bool RemoveUsedBlocks(size_t* start, size_t* length, const SortedRangeSet& used_ranges) {
225 if (!used_ranges.Overlaps(*start, *length)) {
226 return true;
227 }
228
229 // TODO find the largest non-overlap chunk.
230 printf("Removing block %s from %zu - %zu\n", used_ranges.ToString().c_str(), *start,
231 *start + *length - 1);
232
233 // If there's no duplicate entry name, we should only overlap in the head or tail block. Try to
234 // trim both blocks. Skip this source chunk in case it still overlaps with the used ranges.
235 if (AlignHead(start, length) && !used_ranges.Overlaps(*start, *length)) {
236 return true;
237 }
238 if (AlignTail(start, length) && !used_ranges.Overlaps(*start, *length)) {
239 return true;
240 }
241
242 printf("Failed to remove the overlapped block ranges; skip the source\n");
243 return false;
244}
245
246static const struct option OPTIONS[] = {
247 { "zip-mode", no_argument, nullptr, 'z' },
248 { "bonus-file", required_argument, nullptr, 'b' },
249 { "block-limit", required_argument, nullptr, 0 },
250 { "debug-dir", required_argument, nullptr, 0 },
Tianjie Xu82582b42017-08-31 18:05:19 -0700251 { "split-info", required_argument, nullptr, 0 },
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700252 { nullptr, 0, nullptr, 0 },
253};
254
Tianjie Xu57dd9612017-08-17 17:50:56 -0700255ImageChunk::ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content,
256 size_t raw_data_len, std::string entry_name)
257 : type_(type),
258 start_(start),
259 input_file_ptr_(file_content),
260 raw_data_len_(raw_data_len),
261 compress_level_(6),
262 entry_name_(std::move(entry_name)) {
263 CHECK(file_content != nullptr) << "input file container can't be nullptr";
264}
Doug Zongker512536a2010-02-17 16:11:44 -0800265
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800266const uint8_t* ImageChunk::GetRawData() const {
267 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
268 return input_file_ptr_->data() + start_;
269}
270
271const uint8_t * ImageChunk::DataForPatch() const {
272 if (type_ == CHUNK_DEFLATE) {
273 return uncompressed_data_.data();
274 }
275 return GetRawData();
276}
277
278size_t ImageChunk::DataLengthForPatch() const {
279 if (type_ == CHUNK_DEFLATE) {
280 return uncompressed_data_.size();
281 }
282 return raw_data_len_;
283}
284
285bool ImageChunk::operator==(const ImageChunk& other) const {
286 if (type_ != other.type_) {
287 return false;
288 }
289 return (raw_data_len_ == other.raw_data_len_ &&
290 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
291}
292
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800293void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800294 uncompressed_data_ = std::move(data);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800295}
296
297bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
298 if (type_ != CHUNK_DEFLATE) {
299 return false;
300 }
301 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
302 return true;
303}
304
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800305void ImageChunk::ChangeDeflateChunkToNormal() {
306 if (type_ != CHUNK_DEFLATE) return;
307 type_ = CHUNK_NORMAL;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700308 // No need to clear the entry name.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800309 uncompressed_data_.clear();
310}
311
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800312bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
313 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
314 return false;
315 }
316 return (other.start_ == start_ + raw_data_len_);
317}
318
319void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
320 CHECK(IsAdjacentNormal(other));
321 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
322}
323
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700324bool ImageChunk::MakePatch(const ImageChunk& tgt, const ImageChunk& src,
Alex Deymofa188262017-10-10 17:56:17 +0200325 std::vector<uint8_t>* patch_data,
326 bsdiff::SuffixArrayIndexInterface** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700327#if defined(__ANDROID__)
328 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
329#else
330 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
331#endif
332
333 int fd = mkstemp(ptemp);
334 if (fd == -1) {
335 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
336 return false;
337 }
338 close(fd);
339
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700340 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
341 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700342 if (r != 0) {
343 printf("bsdiff() failed: %d\n", r);
344 return false;
345 }
346
347 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
348 if (patch_fd == -1) {
349 printf("failed to open %s: %s\n", ptemp, strerror(errno));
350 return false;
351 }
352 struct stat st;
353 if (fstat(patch_fd, &st) != 0) {
354 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
355 return false;
356 }
357
358 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700359
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700360 patch_data->resize(sz);
361 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
362 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
363 unlink(ptemp);
364 return false;
365 }
366
367 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700368
369 return true;
370}
371
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800372bool ImageChunk::ReconstructDeflateChunk() {
373 if (type_ != CHUNK_DEFLATE) {
374 printf("attempt to reconstruct non-deflate chunk\n");
375 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800376 }
377
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700378 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
379 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800380 for (int level = 6; level <= 9; level += 3) {
381 if (TryReconstruction(level)) {
382 compress_level_ = level;
383 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800384 }
385 }
Doug Zongker512536a2010-02-17 16:11:44 -0800386
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800387 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800388}
389
390/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700391 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
392 * in the chunk, and checks that it matches exactly the compressed data we started with (also
393 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800394 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800395bool ImageChunk::TryReconstruction(int level) {
396 z_stream strm;
397 strm.zalloc = Z_NULL;
398 strm.zfree = Z_NULL;
399 strm.opaque = Z_NULL;
400 strm.avail_in = uncompressed_data_.size();
401 strm.next_in = uncompressed_data_.data();
402 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
403 if (ret < 0) {
404 printf("failed to initialize deflate: %d\n", ret);
405 return false;
406 }
407
408 std::vector<uint8_t> buffer(BUFFER_SIZE);
409 size_t offset = 0;
410 do {
411 strm.avail_out = buffer.size();
412 strm.next_out = buffer.data();
413 ret = deflate(&strm, Z_FINISH);
414 if (ret < 0) {
415 printf("failed to deflate: %d\n", ret);
416 return false;
417 }
418
419 size_t compressed_size = buffer.size() - strm.avail_out;
420 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
421 // mismatch; data isn't the same.
422 deflateEnd(&strm);
423 return false;
424 }
425 offset += compressed_size;
426 } while (ret != Z_STREAM_END);
427 deflateEnd(&strm);
428
429 if (offset != raw_data_len_) {
430 // mismatch; ran out of data before we should have.
431 return false;
432 }
433 return true;
434}
435
Tianjie Xu57dd9612017-08-17 17:50:56 -0700436PatchChunk::PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
437 : type_(tgt.GetType()),
438 source_start_(src.GetStartOffset()),
439 source_len_(src.GetRawDataLength()),
440 source_uncompressed_len_(src.DataLengthForPatch()),
441 target_start_(tgt.GetStartOffset()),
442 target_len_(tgt.GetRawDataLength()),
443 target_uncompressed_len_(tgt.DataLengthForPatch()),
444 target_compress_level_(tgt.GetCompressLevel()),
445 data_(std::move(data)) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700446
Tianjie Xu57dd9612017-08-17 17:50:56 -0700447// Construct a CHUNK_RAW patch from the target data directly.
448PatchChunk::PatchChunk(const ImageChunk& tgt)
449 : type_(CHUNK_RAW),
450 source_start_(0),
451 source_len_(0),
452 source_uncompressed_len_(0),
453 target_start_(tgt.GetStartOffset()),
454 target_len_(tgt.GetRawDataLength()),
455 target_uncompressed_len_(tgt.DataLengthForPatch()),
456 target_compress_level_(tgt.GetCompressLevel()),
457 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700458
459// Return true if raw data is smaller than the patch size.
460bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
461 size_t target_len = tgt.GetRawDataLength();
462 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
463}
464
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700465void PatchChunk::UpdateSourceOffset(const SortedRangeSet& src_range) {
466 if (type_ == CHUNK_DEFLATE) {
467 source_start_ = src_range.GetOffsetInRangeSet(source_start_);
468 }
469}
470
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700471// Header size:
472// header_type 4 bytes
473// CHUNK_NORMAL 8*3 = 24 bytes
474// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
475// CHUNK_RAW 4 bytes + patch_size
476size_t PatchChunk::GetHeaderSize() const {
477 switch (type_) {
478 case CHUNK_NORMAL:
479 return 4 + 8 * 3;
480 case CHUNK_DEFLATE:
481 return 4 + 8 * 5 + 4 * 5;
482 case CHUNK_RAW:
483 return 4 + 4 + data_.size();
484 default:
485 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
486 return 0;
487 }
488}
489
490// Return the offset of the next patch into the patch data.
491size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
492 Write4(fd, type_);
493 switch (type_) {
494 case CHUNK_NORMAL:
495 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
496 Write8(fd, static_cast<int64_t>(source_start_));
497 Write8(fd, static_cast<int64_t>(source_len_));
498 Write8(fd, static_cast<int64_t>(offset));
499 return offset + data_.size();
500 case CHUNK_DEFLATE:
501 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
502 Write8(fd, static_cast<int64_t>(source_start_));
503 Write8(fd, static_cast<int64_t>(source_len_));
504 Write8(fd, static_cast<int64_t>(offset));
505 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
506 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
507 Write4(fd, target_compress_level_);
508 Write4(fd, ImageChunk::METHOD);
509 Write4(fd, ImageChunk::WINDOWBITS);
510 Write4(fd, ImageChunk::MEMLEVEL);
511 Write4(fd, ImageChunk::STRATEGY);
512 return offset + data_.size();
513 case CHUNK_RAW:
514 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
515 Write4(fd, static_cast<int32_t>(data_.size()));
516 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
517 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
518 }
519 return offset;
520 default:
521 CHECK(false) << "unexpected chunk type: " << type_;
522 return offset;
523 }
524}
525
Tianjie Xu82582b42017-08-31 18:05:19 -0700526size_t PatchChunk::PatchSize() const {
527 if (type_ == CHUNK_RAW) {
528 return GetHeaderSize();
529 }
530 return GetHeaderSize() + data_.size();
531}
532
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700533// Write the contents of |patch_chunks| to |patch_fd|.
534bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
535 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
536 // the offset of each bsdiff patch within the file.
537 size_t total_header_size = 12;
538 for (const auto& patch : patch_chunks) {
539 total_header_size += patch.GetHeaderSize();
540 }
541
542 size_t offset = total_header_size;
543
544 // Write out the headers.
Tianjie Xu82582b42017-08-31 18:05:19 -0700545 if (!android::base::WriteStringToFd("IMGDIFF" + std::to_string(VERSION), patch_fd)) {
546 printf("failed to write \"IMGDIFF%zu\": %s\n", VERSION, strerror(errno));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700547 return false;
548 }
549
550 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
551 for (size_t i = 0; i < patch_chunks.size(); ++i) {
552 printf("chunk %zu: ", i);
553 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
554 }
555
556 // Append each chunk's bsdiff patch, in order.
557 for (const auto& patch : patch_chunks) {
558 if (patch.type_ == CHUNK_RAW) {
559 continue;
560 }
561 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
562 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
563 return false;
564 }
565 }
566
567 return true;
568}
569
Tianjie Xu57dd9612017-08-17 17:50:56 -0700570ImageChunk& Image::operator[](size_t i) {
571 CHECK_LT(i, chunks_.size());
572 return chunks_[i];
573}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700574
Tianjie Xu57dd9612017-08-17 17:50:56 -0700575const ImageChunk& Image::operator[](size_t i) const {
576 CHECK_LT(i, chunks_.size());
577 return chunks_[i];
578}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700579
580void Image::MergeAdjacentNormalChunks() {
581 size_t merged_last = 0, cur = 0;
582 while (cur < chunks_.size()) {
583 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
584 // length of the current normal chunk.
585 size_t to_check = cur + 1;
586 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
587 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
588 to_check++;
589 }
590
591 if (merged_last != cur) {
592 chunks_[merged_last] = std::move(chunks_[cur]);
593 }
594 merged_last++;
595 cur = to_check;
596 }
597 if (merged_last < chunks_.size()) {
598 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
599 }
600}
601
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700602void Image::DumpChunks() const {
603 std::string type = is_source_ ? "source" : "target";
604 printf("Dumping chunks for %s\n", type.c_str());
605 for (size_t i = 0; i < chunks_.size(); ++i) {
606 printf("chunk %zu: ", i);
607 chunks_[i].Dump();
608 }
609}
610
611bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
612 CHECK(file_content != nullptr);
613
614 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
615 if (fd == -1) {
616 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
617 return false;
618 }
619 struct stat st;
620 if (fstat(fd, &st) != 0) {
621 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
622 return false;
623 }
624
625 size_t sz = static_cast<size_t>(st.st_size);
626 file_content->resize(sz);
627 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
628 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
629 return false;
630 }
631 fd.reset();
632
633 return true;
634}
635
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700636bool ZipModeImage::Initialize(const std::string& filename) {
637 if (!ReadFile(filename, &file_content_)) {
638 return false;
639 }
640
641 // Omit the trailing zeros before we pass the file to ziparchive handler.
642 size_t zipfile_size;
643 if (!GetZipFileSize(&zipfile_size)) {
644 printf("failed to parse the actual size of %s\n", filename.c_str());
645 return false;
646 }
647 ZipArchiveHandle handle;
648 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
649 filename.c_str(), &handle);
650 if (err != 0) {
651 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
652 CloseArchive(handle);
653 return false;
654 }
655
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700656 if (!InitializeChunks(filename, handle)) {
657 CloseArchive(handle);
658 return false;
659 }
660
661 CloseArchive(handle);
662 return true;
663}
664
665// Iterate the zip entries and compose the image chunks accordingly.
666bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
667 void* cookie;
668 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
669 if (ret != 0) {
670 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
671 return false;
672 }
673
674 // Create a list of deflated zip entries, sorted by offset.
675 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
676 ZipString name;
677 ZipEntry entry;
678 while ((ret = Next(cookie, &entry, &name)) == 0) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700679 if (entry.method == kCompressDeflated || limit_ > 0) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700680 std::string entry_name(name.name, name.name + name.name_length);
681 temp_entries.emplace_back(entry_name, entry);
682 }
683 }
684
685 if (ret != -1) {
686 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
687 return false;
688 }
689 std::sort(temp_entries.begin(), temp_entries.end(),
690 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
691
692 EndIteration(cookie);
693
694 // For source chunks, we don't need to compose chunks for the metadata.
695 if (is_source_) {
696 for (auto& entry : temp_entries) {
697 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
698 printf("Failed to add %s to source chunks\n", entry.first.c_str());
699 return false;
700 }
701 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700702
703 // Add the end of zip file (mainly central directory) as a normal chunk.
704 size_t entries_end = 0;
705 if (!temp_entries.empty()) {
706 entries_end = static_cast<size_t>(temp_entries.back().second.offset +
707 temp_entries.back().second.compressed_length);
708 }
709 CHECK_LT(entries_end, file_content_.size());
710 chunks_.emplace_back(CHUNK_NORMAL, entries_end, &file_content_,
711 file_content_.size() - entries_end);
712
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700713 return true;
714 }
715
716 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
717 // deflate entries as CHUNK_NORMAL.
718 size_t pos = 0;
719 size_t nextentry = 0;
720 while (pos < file_content_.size()) {
721 if (nextentry < temp_entries.size() &&
722 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
723 // Add the next zip entry.
724 std::string entry_name = temp_entries[nextentry].first;
725 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
726 printf("Failed to add %s to target chunks\n", entry_name.c_str());
727 return false;
728 }
729
730 pos += temp_entries[nextentry].second.compressed_length;
731 ++nextentry;
732 continue;
733 }
734
735 // Use a normal chunk to take all the data up to the start of the next entry.
736 size_t raw_data_len;
737 if (nextentry < temp_entries.size()) {
738 raw_data_len = temp_entries[nextentry].second.offset - pos;
739 } else {
740 raw_data_len = file_content_.size() - pos;
741 }
742 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
743
744 pos += raw_data_len;
745 }
746
747 return true;
748}
749
750bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
751 ZipEntry* entry) {
752 size_t compressed_len = entry->compressed_length;
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700753 if (compressed_len == 0) return true;
754
755 // Split the entry into several normal chunks if it's too large.
756 if (limit_ > 0 && compressed_len > limit_) {
757 int count = 0;
758 while (compressed_len > 0) {
759 size_t length = std::min(limit_, compressed_len);
760 std::string name = entry_name + "-" + std::to_string(count);
761 chunks_.emplace_back(CHUNK_NORMAL, entry->offset + limit_ * count, &file_content_, length,
762 name);
763
764 count++;
765 compressed_len -= length;
766 }
767 } else if (entry->method == kCompressDeflated) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700768 size_t uncompressed_len = entry->uncompressed_length;
769 std::vector<uint8_t> uncompressed_data(uncompressed_len);
770 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
771 if (ret != 0) {
772 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
773 ErrorCodeString(ret));
774 return false;
775 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700776 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700777 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700778 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700779 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700780 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700781 }
782
783 return true;
784}
785
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800786// EOCD record
787// offset 0: signature 0x06054b50, 4 bytes
788// offset 4: number of this disk, 2 bytes
789// ...
790// offset 20: comment length, 2 bytes
791// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700792bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
793 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800794 printf("file is too small to be a zip file\n");
795 return false;
796 }
797
798 // Look for End of central directory record of the zip file, and calculate the actual
799 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700800 for (int i = file_content_.size() - 22; i >= 0; i--) {
801 if (file_content_[i] == 0x50) {
802 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800803 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700804 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800805
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700806 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800807 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700808 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800809 *input_file_size = file_size;
810 return true;
811 }
812 }
813 }
814
815 // EOCD not found, this file is likely not a valid zip file.
816 return false;
817}
818
Tianjie Xu57dd9612017-08-17 17:50:56 -0700819ImageChunk ZipModeImage::PseudoSource() const {
820 CHECK(is_source_);
821 return ImageChunk(CHUNK_NORMAL, 0, &file_content_, file_content_.size());
822}
823
824const ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) const {
825 if (name.empty()) {
826 return nullptr;
827 }
828 for (auto& chunk : chunks_) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700829 if (chunk.GetType() != CHUNK_DEFLATE && !find_normal) {
830 continue;
831 }
832
833 if (chunk.GetEntryName() == name) {
Tianjie Xu57dd9612017-08-17 17:50:56 -0700834 return &chunk;
835 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700836
837 // Edge case when target chunk is split due to size limit but source chunk isn't.
838 if (name == (chunk.GetEntryName() + "-0") || chunk.GetEntryName() == (name + "-0")) {
839 return &chunk;
840 }
841
842 // TODO handle the .so files with incremental version number.
843 // (e.g. lib/arm64-v8a/libcronet.59.0.3050.4.so)
Tianjie Xu57dd9612017-08-17 17:50:56 -0700844 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700845
Tianjie Xu57dd9612017-08-17 17:50:56 -0700846 return nullptr;
847}
848
849ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) {
850 return const_cast<ImageChunk*>(
851 static_cast<const ZipModeImage*>(this)->FindChunkByName(name, find_normal));
852}
853
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700854bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
855 for (auto& tgt_chunk : *tgt_image) {
856 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800857 continue;
858 }
859
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700860 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
861 if (src_chunk == nullptr) {
862 tgt_chunk.ChangeDeflateChunkToNormal();
863 } else if (tgt_chunk == *src_chunk) {
864 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
865 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
866 // patch to the compressed data, rather than uncompressing and recompressing to apply the
867 // trivial patch to the uncompressed data.
868 tgt_chunk.ChangeDeflateChunkToNormal();
869 src_chunk->ChangeDeflateChunkToNormal();
870 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
871 // We cannot recompress the data and get exactly the same bits as are in the input target
872 // image. Treat the chunk as a normal non-deflated chunk.
873 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
874 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800875
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700876 tgt_chunk.ChangeDeflateChunkToNormal();
877 src_chunk->ChangeDeflateChunkToNormal();
878 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800879 }
880
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700881 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
882 // filename, and normal chunks are patched using the entire source file as the source.
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700883 if (tgt_image->limit_ == 0) {
884 tgt_image->MergeAdjacentNormalChunks();
885 tgt_image->DumpChunks();
886 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800887
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700888 return true;
889}
890
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700891// For each target chunk, look for the corresponding source chunk by the zip_entry name. If
892// found, add the range of this chunk in the original source file to the block aligned source
893// ranges. Construct the split src & tgt image once the size of source range reaches limit.
894bool ZipModeImage::SplitZipModeImageWithLimit(const ZipModeImage& tgt_image,
895 const ZipModeImage& src_image,
896 std::vector<ZipModeImage>* split_tgt_images,
897 std::vector<ZipModeImage>* split_src_images,
898 std::vector<SortedRangeSet>* split_src_ranges) {
899 CHECK_EQ(tgt_image.limit_, src_image.limit_);
900 size_t limit = tgt_image.limit_;
901
902 src_image.DumpChunks();
903 printf("Splitting %zu tgt chunks...\n", tgt_image.NumOfChunks());
904
905 SortedRangeSet used_src_ranges; // ranges used for previous split source images.
906
907 // Reserve the central directory in advance for the last split image.
908 const auto& central_directory = src_image.cend() - 1;
909 CHECK_EQ(CHUNK_NORMAL, central_directory->GetType());
910 used_src_ranges.Insert(central_directory->GetStartOffset(),
911 central_directory->DataLengthForPatch());
912
913 SortedRangeSet src_ranges;
914 std::vector<ImageChunk> split_src_chunks;
915 std::vector<ImageChunk> split_tgt_chunks;
916 for (auto tgt = tgt_image.cbegin(); tgt != tgt_image.cend(); tgt++) {
917 const ImageChunk* src = src_image.FindChunkByName(tgt->GetEntryName(), true);
918 if (src == nullptr) {
919 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
920 tgt->GetRawDataLength());
921 continue;
922 }
923
924 size_t src_offset = src->GetStartOffset();
925 size_t src_length = src->GetRawDataLength();
926
927 CHECK(src_length > 0);
928 CHECK_LE(src_length, limit);
929
930 // Make sure this source range hasn't been used before so that the src_range pieces don't
931 // overlap with each other.
932 if (!RemoveUsedBlocks(&src_offset, &src_length, used_src_ranges)) {
933 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
934 tgt->GetRawDataLength());
935 } else if (src_ranges.blocks() * BLOCK_SIZE + src_length <= limit) {
936 src_ranges.Insert(src_offset, src_length);
937
938 // Add the deflate source chunk if it hasn't been aligned.
939 if (src->GetType() == CHUNK_DEFLATE && src_length == src->GetRawDataLength()) {
940 split_src_chunks.push_back(*src);
941 split_tgt_chunks.push_back(*tgt);
942 } else {
943 // TODO split smarter to avoid alignment of large deflate chunks
944 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
945 tgt->GetRawDataLength());
946 }
947 } else {
948 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
949 split_src_chunks, split_tgt_images,
950 split_src_images);
951
952 split_tgt_chunks.clear();
953 split_src_chunks.clear();
954 used_src_ranges.Insert(src_ranges);
955 split_src_ranges->push_back(std::move(src_ranges));
956 src_ranges.Clear();
957
958 // We don't have enough space for the current chunk; start a new split image and handle
959 // this chunk there.
960 tgt--;
961 }
962 }
963
964 // TODO Trim it in case the CD exceeds limit too much.
965 src_ranges.Insert(central_directory->GetStartOffset(), central_directory->DataLengthForPatch());
966 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
967 split_src_chunks, split_tgt_images, split_src_images);
968 split_src_ranges->push_back(std::move(src_ranges));
969
970 ValidateSplitImages(*split_tgt_images, *split_src_images, *split_src_ranges,
971 tgt_image.file_content_.size());
972
973 return true;
974}
975
976void ZipModeImage::AddSplitImageFromChunkList(const ZipModeImage& tgt_image,
977 const ZipModeImage& src_image,
978 const SortedRangeSet& split_src_ranges,
979 const std::vector<ImageChunk>& split_tgt_chunks,
980 const std::vector<ImageChunk>& split_src_chunks,
981 std::vector<ZipModeImage>* split_tgt_images,
982 std::vector<ZipModeImage>* split_src_images) {
983 CHECK(!split_tgt_chunks.empty());
984 // Target chunks should occupy at least one block.
985 // TODO put a warning and change the type to raw if it happens in extremely rare cases.
986 size_t tgt_size = split_tgt_chunks.back().GetStartOffset() +
987 split_tgt_chunks.back().DataLengthForPatch() -
988 split_tgt_chunks.front().GetStartOffset();
989 CHECK_GE(tgt_size, BLOCK_SIZE);
990
991 std::vector<ImageChunk> aligned_tgt_chunks;
992
993 // Align the target chunks in the beginning with BLOCK_SIZE.
994 size_t i = 0;
995 while (i < split_tgt_chunks.size()) {
996 size_t tgt_start = split_tgt_chunks[i].GetStartOffset();
997 size_t tgt_length = split_tgt_chunks[i].GetRawDataLength();
998
999 // Current ImageChunk is long enough to align.
1000 if (AlignHead(&tgt_start, &tgt_length)) {
1001 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt_start, &tgt_image.file_content_,
1002 tgt_length);
1003 break;
1004 }
1005
1006 i++;
1007 }
1008 CHECK_LT(i, split_tgt_chunks.size());
1009 aligned_tgt_chunks.insert(aligned_tgt_chunks.end(), split_tgt_chunks.begin() + i + 1,
1010 split_tgt_chunks.end());
1011 CHECK(!aligned_tgt_chunks.empty());
1012
1013 // Add a normal chunk to align the contents in the end.
1014 size_t end_offset =
1015 aligned_tgt_chunks.back().GetStartOffset() + aligned_tgt_chunks.back().GetRawDataLength();
1016 if (end_offset % BLOCK_SIZE != 0 && end_offset < tgt_image.file_content_.size()) {
1017 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, end_offset, &tgt_image.file_content_,
1018 BLOCK_SIZE - (end_offset % BLOCK_SIZE));
1019 }
1020
1021 ZipModeImage split_tgt_image(false);
1022 split_tgt_image.Initialize(std::move(aligned_tgt_chunks), {});
1023 split_tgt_image.MergeAdjacentNormalChunks();
1024
1025 // Construct the dummy source file based on the src_ranges.
1026 std::vector<uint8_t> src_content;
1027 for (const auto& r : split_src_ranges) {
1028 size_t end = std::min(src_image.file_content_.size(), r.second * BLOCK_SIZE);
1029 src_content.insert(src_content.end(), src_image.file_content_.begin() + r.first * BLOCK_SIZE,
1030 src_image.file_content_.begin() + end);
1031 }
1032
1033 // We should not have an empty src in our design; otherwise we will encounter an error in
1034 // bsdiff since src_content.data() == nullptr.
1035 CHECK(!src_content.empty());
1036
1037 ZipModeImage split_src_image(true);
1038 split_src_image.Initialize(split_src_chunks, std::move(src_content));
1039
1040 split_tgt_images->push_back(std::move(split_tgt_image));
1041 split_src_images->push_back(std::move(split_src_image));
1042}
1043
1044void ZipModeImage::ValidateSplitImages(const std::vector<ZipModeImage>& split_tgt_images,
1045 const std::vector<ZipModeImage>& split_src_images,
1046 std::vector<SortedRangeSet>& split_src_ranges,
1047 size_t total_tgt_size) {
1048 CHECK_EQ(split_tgt_images.size(), split_src_images.size());
1049
1050 printf("Validating %zu images\n", split_tgt_images.size());
1051
1052 // Verify that the target image pieces is continuous and can add up to the total size.
1053 size_t last_offset = 0;
1054 for (const auto& tgt_image : split_tgt_images) {
1055 CHECK(!tgt_image.chunks_.empty());
1056
1057 CHECK_EQ(last_offset, tgt_image.chunks_.front().GetStartOffset());
1058 CHECK(last_offset % BLOCK_SIZE == 0);
1059
1060 // Check the target chunks within the split image are continuous.
1061 for (const auto& chunk : tgt_image.chunks_) {
1062 CHECK_EQ(last_offset, chunk.GetStartOffset());
1063 last_offset += chunk.GetRawDataLength();
1064 }
1065 }
1066 CHECK_EQ(total_tgt_size, last_offset);
1067
1068 // Verify that the source ranges are mutually exclusive.
1069 CHECK_EQ(split_src_images.size(), split_src_ranges.size());
1070 SortedRangeSet used_src_ranges;
1071 for (size_t i = 0; i < split_src_ranges.size(); i++) {
1072 CHECK(!used_src_ranges.Overlaps(split_src_ranges[i]))
1073 << "src range " << split_src_ranges[i].ToString() << " overlaps "
1074 << used_src_ranges.ToString();
1075 used_src_ranges.Insert(split_src_ranges[i]);
1076 }
1077}
1078
1079bool ZipModeImage::GeneratePatchesInternal(const ZipModeImage& tgt_image,
1080 const ZipModeImage& src_image,
1081 std::vector<PatchChunk>* patch_chunks) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001082 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001083 patch_chunks->clear();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001084
Alex Deymofa188262017-10-10 17:56:17 +02001085 bsdiff::SuffixArrayIndexInterface* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001086 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1087 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001088
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001089 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001090 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001091 continue;
1092 }
1093
1094 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
1095 ? nullptr
1096 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
1097
1098 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Alex Deymofa188262017-10-10 17:56:17 +02001099 bsdiff::SuffixArrayIndexInterface** bsdiff_cache_ptr =
1100 (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001101
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001102 std::vector<uint8_t> patch_data;
1103 if (!ImageChunk::MakePatch(tgt_chunk, src_ref, &patch_data, bsdiff_cache_ptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001104 printf("Failed to generate patch, name: %s\n", tgt_chunk.GetEntryName().c_str());
1105 return false;
1106 }
1107
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001108 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001109 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001110
1111 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001112 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001113 } else {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001114 patch_chunks->emplace_back(tgt_chunk, src_ref, std::move(patch_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001115 }
Tianjie Xu12b90552017-03-07 14:44:14 -08001116 }
Alex Deymofa188262017-10-10 17:56:17 +02001117 delete bsdiff_cache;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001118
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001119 CHECK_EQ(patch_chunks->size(), tgt_image.NumOfChunks());
1120 return true;
1121}
1122
1123bool ZipModeImage::GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
1124 const std::string& patch_name) {
1125 std::vector<PatchChunk> patch_chunks;
1126
1127 ZipModeImage::GeneratePatchesInternal(tgt_image, src_image, &patch_chunks);
1128
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001129 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1130
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001131 android::base::unique_fd patch_fd(
1132 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1133 if (patch_fd == -1) {
1134 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001135 return false;
1136 }
1137
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001138 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001139}
1140
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001141bool ZipModeImage::GeneratePatches(const std::vector<ZipModeImage>& split_tgt_images,
1142 const std::vector<ZipModeImage>& split_src_images,
1143 const std::vector<SortedRangeSet>& split_src_ranges,
Tianjie Xu82582b42017-08-31 18:05:19 -07001144 const std::string& patch_name,
1145 const std::string& split_info_file,
1146 const std::string& debug_dir) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001147 printf("Construct patches for %zu split images...\n", split_tgt_images.size());
1148
1149 android::base::unique_fd patch_fd(
1150 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1151 if (patch_fd == -1) {
1152 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1153 return false;
1154 }
1155
Tianjie Xu82582b42017-08-31 18:05:19 -07001156 std::vector<std::string> split_info_list;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001157 for (size_t i = 0; i < split_tgt_images.size(); i++) {
1158 std::vector<PatchChunk> patch_chunks;
1159 if (!ZipModeImage::GeneratePatchesInternal(split_tgt_images[i], split_src_images[i],
1160 &patch_chunks)) {
1161 printf("failed to generate split patch\n");
1162 return false;
1163 }
1164
Tianjie Xu82582b42017-08-31 18:05:19 -07001165 size_t total_patch_size = 12;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001166 for (auto& p : patch_chunks) {
1167 p.UpdateSourceOffset(split_src_ranges[i]);
Tianjie Xu82582b42017-08-31 18:05:19 -07001168 total_patch_size += p.PatchSize();
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001169 }
1170
1171 if (!PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd)) {
1172 return false;
1173 }
1174
Tianjie Xu82582b42017-08-31 18:05:19 -07001175 size_t split_tgt_size = split_tgt_images[i].chunks_.back().GetStartOffset() +
1176 split_tgt_images[i].chunks_.back().GetRawDataLength() -
1177 split_tgt_images[i].chunks_.front().GetStartOffset();
1178 std::string split_info = android::base::StringPrintf(
1179 "%zu %zu %s", total_patch_size, split_tgt_size, split_src_ranges[i].ToString().c_str());
1180 split_info_list.push_back(split_info);
1181
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001182 // Write the split source & patch into the debug directory.
1183 if (!debug_dir.empty()) {
1184 std::string src_name = android::base::StringPrintf("%s/src-%zu", debug_dir.c_str(), i);
1185 android::base::unique_fd fd(
1186 open(src_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1187
1188 if (fd == -1) {
1189 printf("Failed to open %s\n", src_name.c_str());
1190 return false;
1191 }
1192 if (!android::base::WriteFully(fd, split_src_images[i].PseudoSource().DataForPatch(),
1193 split_src_images[i].PseudoSource().DataLengthForPatch())) {
1194 printf("Failed to write split source data into %s\n", src_name.c_str());
1195 return false;
1196 }
1197
1198 std::string patch_name = android::base::StringPrintf("%s/patch-%zu", debug_dir.c_str(), i);
1199 fd.reset(open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1200
1201 if (fd == -1) {
1202 printf("Failed to open %s\n", patch_name.c_str());
1203 return false;
1204 }
1205 if (!PatchChunk::WritePatchDataToFd(patch_chunks, fd)) {
1206 return false;
1207 }
1208 }
1209 }
Tianjie Xu82582b42017-08-31 18:05:19 -07001210
1211 // Store the split in the following format:
1212 // Line 0: imgdiff version#
1213 // Line 1: number of pieces
1214 // Line 2: patch_size_1 tgt_size_1 src_range_1
1215 // ...
1216 // Line n+1: patch_size_n tgt_size_n src_range_n
1217 std::string split_info_string = android::base::StringPrintf(
1218 "%zu\n%zu\n", VERSION, split_info_list.size()) + android::base::Join(split_info_list, '\n');
1219 if (!android::base::WriteStringToFile(split_info_string, split_info_file)) {
1220 printf("failed to write split info to \"%s\": %s\n", split_info_file.c_str(),
1221 strerror(errno));
1222 return false;
1223 }
1224
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001225 return true;
1226}
1227
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001228bool ImageModeImage::Initialize(const std::string& filename) {
1229 if (!ReadFile(filename, &file_content_)) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001230 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001231 }
Doug Zongker512536a2010-02-17 16:11:44 -08001232
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001233 size_t sz = file_content_.size();
Doug Zongker512536a2010-02-17 16:11:44 -08001234 size_t pos = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -07001235 while (pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001236 // 0x00 no header flags, 0x08 deflate compression, 0x1f8b gzip magic number
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001237 if (sz - pos >= 4 && get_unaligned<uint32_t>(file_content_.data() + pos) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001238 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +02001239 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001240
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001241 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
1242 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001243 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, sz - pos);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001244 break;
1245 }
Doug Zongker512536a2010-02-17 16:11:44 -08001246
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001247 // We need three chunks for the deflated image in total, one normal chunk for the header,
1248 // one deflated chunk for the body, and another normal chunk for the footer.
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001249 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_HEADER_LEN);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001250 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001251
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001252 // We must decompress this chunk in order to discover where it ends, and so we can update
1253 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -08001254
1255 z_stream strm;
1256 strm.zalloc = Z_NULL;
1257 strm.zfree = Z_NULL;
1258 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -07001259 strm.avail_in = sz - pos;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001260 strm.next_in = file_content_.data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001261
1262 // -15 means we are decoding a 'raw' deflate stream; zlib will
1263 // not expect zlib headers.
1264 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001265 if (ret < 0) {
1266 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001267 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001268 }
Doug Zongker512536a2010-02-17 16:11:44 -08001269
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001270 size_t allocated = BUFFER_SIZE;
1271 std::vector<uint8_t> uncompressed_data(allocated);
1272 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001273 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001274 strm.avail_out = allocated - uncompressed_len;
1275 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001276 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +02001277 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001278 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -08001279 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001280 break;
Johan Redestigc68bd342015-04-14 21:20:06 +02001281 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001282 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -08001283 if (strm.avail_out == 0) {
1284 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001285 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -08001286 }
1287 } while (ret != Z_STREAM_END);
1288
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001289 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001290 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001291
1292 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001293 continue;
1294 }
1295
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001296 // The footer contains the size of the uncompressed data. Double-check to make sure that it
1297 // matches the size of the data we got when we actually did the decompression.
1298 size_t footer_index = pos + raw_data_len + GZIP_FOOTER_LEN - 4;
1299 if (sz - footer_index < 4) {
1300 printf("Warning: invalid footer position; treating as a nomal chunk\n");
1301 continue;
1302 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001303 size_t footer_size = get_unaligned<uint32_t>(file_content_.data() + footer_index);
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001304 if (footer_size != uncompressed_len) {
1305 printf("Warning: footer size %zu != decompressed size %zu; treating as a nomal chunk\n",
1306 footer_size, uncompressed_len);
1307 continue;
1308 }
1309
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001310 ImageChunk body(CHUNK_DEFLATE, pos, &file_content_, raw_data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001311 uncompressed_data.resize(uncompressed_len);
1312 body.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001313 chunks_.push_back(std::move(body));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001314
1315 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001316
1317 // create a normal chunk for the footer
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001318 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -08001319
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001320 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001321 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001322 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
1323 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -08001324
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001325 // Scan forward until we find a gzip header.
1326 size_t data_len = 0;
1327 while (data_len + pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001328 if (data_len + pos + 4 <= sz &&
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001329 get_unaligned<uint32_t>(file_content_.data() + pos + data_len) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001330 break;
1331 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001332 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -08001333 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001334 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001335
1336 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001337 }
1338 }
1339
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001340 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001341}
1342
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001343bool ImageModeImage::SetBonusData(const std::vector<uint8_t>& bonus_data) {
1344 CHECK(is_source_);
1345 if (chunks_.size() < 2 || !chunks_[1].SetBonusData(bonus_data)) {
1346 printf("Failed to set bonus data\n");
1347 DumpChunks();
1348 return false;
1349 }
1350
1351 printf(" using %zu bytes of bonus data\n", bonus_data.size());
1352 return true;
1353}
1354
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001355// In Image Mode, verify that the source and target images have the same chunk structure (ie, the
1356// same sequence of deflate and normal chunks).
1357bool ImageModeImage::CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image) {
1358 // In image mode, merge the gzip header and footer in with any adjacent normal chunks.
1359 tgt_image->MergeAdjacentNormalChunks();
1360 src_image->MergeAdjacentNormalChunks();
Doug Zongker512536a2010-02-17 16:11:44 -08001361
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001362 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1363 printf("source and target don't have same number of chunks!\n");
1364 tgt_image->DumpChunks();
1365 src_image->DumpChunks();
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001366 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +02001367 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001368 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001369 if ((*tgt_image)[i].GetType() != (*src_image)[i].GetType()) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001370 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
1371 tgt_image->DumpChunks();
1372 src_image->DumpChunks();
1373 return false;
1374 }
Doug Zongker512536a2010-02-17 16:11:44 -08001375 }
1376
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001377 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001378 auto& tgt_chunk = (*tgt_image)[i];
1379 auto& src_chunk = (*src_image)[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001380 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
1381 continue;
1382 }
1383
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001384 // If two deflate chunks are identical treat them as normal chunks.
1385 if (tgt_chunk == src_chunk) {
1386 tgt_chunk.ChangeDeflateChunkToNormal();
1387 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001388 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
1389 // We cannot recompress the data and get exactly the same bits as are in the input target
1390 // image, fall back to normal
1391 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
1392 tgt_chunk.GetEntryName().c_str());
1393 tgt_chunk.ChangeDeflateChunkToNormal();
1394 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001395 }
Doug Zongker512536a2010-02-17 16:11:44 -08001396 }
1397
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001398 // For images, we need to maintain the parallel structure of the chunk lists, so do the merging
1399 // in both the source and target lists.
1400 tgt_image->MergeAdjacentNormalChunks();
1401 src_image->MergeAdjacentNormalChunks();
1402 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1403 // This shouldn't happen.
1404 printf("merging normal chunks went awry\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001405 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001406 }
Doug Zongker512536a2010-02-17 16:11:44 -08001407
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001408 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001409}
1410
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001411// In image mode, generate patches against the given source chunks and bonus_data; write the
1412// result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001413bool ImageModeImage::GeneratePatches(const ImageModeImage& tgt_image,
1414 const ImageModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001415 const std::string& patch_name) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001416 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
1417 std::vector<PatchChunk> patch_chunks;
1418 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001419
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001420 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1421 const auto& tgt_chunk = tgt_image[i];
1422 const auto& src_chunk = src_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001423
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001424 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
1425 patch_chunks.emplace_back(tgt_chunk);
1426 continue;
Doug Zongker512536a2010-02-17 16:11:44 -08001427 }
1428
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001429 std::vector<uint8_t> patch_data;
1430 if (!ImageChunk::MakePatch(tgt_chunk, src_chunk, &patch_data, nullptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001431 printf("Failed to generate patch for target chunk %zu: ", i);
1432 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001433 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001434 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001435 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001436
1437 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
1438 patch_chunks.emplace_back(tgt_chunk);
1439 } else {
1440 patch_chunks.emplace_back(tgt_chunk, src_chunk, std::move(patch_data));
1441 }
Doug Zongker512536a2010-02-17 16:11:44 -08001442 }
Doug Zongker512536a2010-02-17 16:11:44 -08001443
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001444 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1445
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001446 android::base::unique_fd patch_fd(
1447 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1448 if (patch_fd == -1) {
1449 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1450 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001451 }
Doug Zongker512536a2010-02-17 16:11:44 -08001452
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001453 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Doug Zongker512536a2010-02-17 16:11:44 -08001454}
1455
Tao Bao97555da2016-12-15 10:15:06 -08001456int imgdiff(int argc, const char** argv) {
1457 bool zip_mode = false;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001458 std::vector<uint8_t> bonus_data;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001459 size_t blocks_limit = 0;
Tianjie Xu82582b42017-08-31 18:05:19 -07001460 std::string split_info_file;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001461 std::string debug_dir;
Tianjie Xu12b90552017-03-07 14:44:14 -08001462
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001463 int opt;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001464 int option_index;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001465 optind = 1; // Reset the getopt state so that we can call it multiple times for test.
Doug Zongkera3ccba62012-08-20 15:28:02 -07001466
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001467 while ((opt = getopt_long(argc, const_cast<char**>(argv), "zb:", OPTIONS, &option_index)) != -1) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001468 switch (opt) {
1469 case 'z':
1470 zip_mode = true;
1471 break;
1472 case 'b': {
1473 android::base::unique_fd fd(open(optarg, O_RDONLY));
1474 if (fd == -1) {
1475 printf("failed to open bonus file %s: %s\n", optarg, strerror(errno));
1476 return 1;
1477 }
1478 struct stat st;
1479 if (fstat(fd, &st) != 0) {
1480 printf("failed to stat bonus file %s: %s\n", optarg, strerror(errno));
1481 return 1;
1482 }
1483
1484 size_t bonus_size = st.st_size;
1485 bonus_data.resize(bonus_size);
1486 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
1487 printf("failed to read bonus file %s: %s\n", optarg, strerror(errno));
1488 return 1;
1489 }
1490 break;
1491 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001492 case 0: {
1493 std::string name = OPTIONS[option_index].name;
1494 if (name == "block-limit" && !android::base::ParseUint(optarg, &blocks_limit)) {
1495 printf("failed to parse size blocks_limit: %s\n", optarg);
1496 return 1;
Tianjie Xu82582b42017-08-31 18:05:19 -07001497 } else if (name == "split-info") {
1498 split_info_file = optarg;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001499 } else if (name == "debug-dir") {
1500 debug_dir = optarg;
1501 }
1502 break;
1503 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001504 default:
1505 printf("unexpected opt: %s\n", optarg);
1506 return 2;
1507 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001508 }
1509
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001510 if (argc - optind != 3) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001511 printf("usage: %s [options] <src-img> <tgt-img> <patch-file>\n", argv[0]);
1512 printf(
1513 " -z <zip-mode>, Generate patches in zip mode, src and tgt should be zip files.\n"
1514 " -b <bonus-file>, Bonus file in addition to src, image mode only.\n"
1515 " --block-limit, For large zips, split the src and tgt based on the block limit;\n"
1516 " and generate patches between each pair of pieces. Concatenate these\n"
1517 " patches together and output them into <patch-file>.\n"
Tianjie Xu82582b42017-08-31 18:05:19 -07001518 " --split-info, Output the split information (patch_size, tgt_size, src_ranges);\n"
1519 " zip mode with block-limit only.\n"
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001520 " --debug_dir, Debug directory to put the split srcs and patches, zip mode only.\n");
Doug Zongkera3ccba62012-08-20 15:28:02 -07001521 return 2;
1522 }
Doug Zongker512536a2010-02-17 16:11:44 -08001523
Doug Zongker512536a2010-02-17 16:11:44 -08001524 if (zip_mode) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001525 ZipModeImage src_image(true, blocks_limit * BLOCK_SIZE);
1526 ZipModeImage tgt_image(false, blocks_limit * BLOCK_SIZE);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001527
1528 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001529 return 1;
1530 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001531 if (!tgt_image.Initialize(argv[optind + 1])) {
1532 return 1;
1533 }
1534
1535 if (!ZipModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
1536 return 1;
1537 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001538
1539 // TODO save and output the split information so that caller can create split transfer lists
1540 // accordingly.
1541
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001542 // Compute bsdiff patches for each chunk's data (the uncompressed data, in the case of
1543 // deflate chunks).
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001544 if (blocks_limit > 0) {
Tianjie Xu82582b42017-08-31 18:05:19 -07001545 if (split_info_file.empty()) {
1546 printf("split-info path cannot be empty when generating patches with a block-limit.\n");
1547 return 1;
1548 }
1549
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001550 std::vector<ZipModeImage> split_tgt_images;
1551 std::vector<ZipModeImage> split_src_images;
1552 std::vector<SortedRangeSet> split_src_ranges;
1553 ZipModeImage::SplitZipModeImageWithLimit(tgt_image, src_image, &split_tgt_images,
1554 &split_src_images, &split_src_ranges);
1555
1556 if (!ZipModeImage::GeneratePatches(split_tgt_images, split_src_images, split_src_ranges,
Tianjie Xu82582b42017-08-31 18:05:19 -07001557 argv[optind + 2], split_info_file, debug_dir)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001558 return 1;
1559 }
1560
1561 } else if (!ZipModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001562 return 1;
1563 }
1564 } else {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001565 ImageModeImage src_image(true);
1566 ImageModeImage tgt_image(false);
1567
1568 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001569 return 1;
1570 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001571 if (!tgt_image.Initialize(argv[optind + 1])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001572 return 1;
1573 }
1574
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001575 if (!ImageModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
Doug Zongker512536a2010-02-17 16:11:44 -08001576 return 1;
1577 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001578
1579 if (!bonus_data.empty() && !src_image.SetBonusData(bonus_data)) {
1580 return 1;
1581 }
1582
1583 if (!ImageModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001584 return 1;
1585 }
1586 }
1587
Doug Zongker512536a2010-02-17 16:11:44 -08001588 return 0;
1589}