blob: f57e7942cc6ffede1a05476534cdb4a8ff89e980 [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 Bao45685822017-10-13 14:54:12 -0700163#include <android-base/stringprintf.h>
164#include <android-base/strings.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800165#include <android-base/unique_fd.h>
Alex Deymofa188262017-10-10 17:56:17 +0200166#include <bsdiff/bsdiff.h>
Tianjie Xu57dd9612017-08-17 17:50:56 -0700167#include <ziparchive/zip_archive.h>
Tao Bao97555da2016-12-15 10:15:06 -0800168#include <zlib.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700169
Tianjie Xu57dd9612017-08-17 17:50:56 -0700170#include "applypatch/imgdiff_image.h"
Tao Bao09e468f2017-09-29 14:39:33 -0700171#include "otautil/rangeset.h"
Tianjie Xu57dd9612017-08-17 17:50:56 -0700172
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800173using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800174
Tianjie Xu82582b42017-08-31 18:05:19 -0700175static constexpr size_t VERSION = 2;
176
177// We assume the header "IMGDIFF#" is 8 bytes.
178static_assert(VERSION <= 9, "VERSION occupies more than one byte.");
179
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700180static constexpr size_t BLOCK_SIZE = 4096;
181static constexpr size_t BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800182
Tianjie Xu12b90552017-03-07 14:44:14 -0800183// If we use this function to write the offset and length (type size_t), their values should not
184// exceed 2^63; because the signed bit will be casted away.
185static inline bool Write8(int fd, int64_t value) {
186 return android::base::WriteFully(fd, &value, sizeof(int64_t));
187}
188
189// Similarly, the value should not exceed 2^31 if we are casting from size_t (e.g. target chunk
190// size).
191static inline bool Write4(int fd, int32_t value) {
192 return android::base::WriteFully(fd, &value, sizeof(int32_t));
193}
194
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700195// Trim the head or tail to align with the block size. Return false if the chunk has nothing left
196// after alignment.
197static bool AlignHead(size_t* start, size_t* length) {
198 size_t residual = (*start % BLOCK_SIZE == 0) ? 0 : BLOCK_SIZE - *start % BLOCK_SIZE;
199
200 if (*length <= residual) {
201 *length = 0;
202 return false;
203 }
204
205 // Trim the data in the beginning.
206 *start += residual;
207 *length -= residual;
208 return true;
209}
210
211static bool AlignTail(size_t* start, size_t* length) {
212 size_t residual = (*start + *length) % BLOCK_SIZE;
213 if (*length <= residual) {
214 *length = 0;
215 return false;
216 }
217
218 // Trim the data in the end.
219 *length -= residual;
220 return true;
221}
222
223// Remove the used blocks from the source chunk to make sure the source ranges are mutually
224// exclusive after split. Return false if we fail to get the non-overlapped ranges. In such
225// a case, we'll skip the entire source chunk.
226static bool RemoveUsedBlocks(size_t* start, size_t* length, const SortedRangeSet& used_ranges) {
227 if (!used_ranges.Overlaps(*start, *length)) {
228 return true;
229 }
230
231 // TODO find the largest non-overlap chunk.
232 printf("Removing block %s from %zu - %zu\n", used_ranges.ToString().c_str(), *start,
233 *start + *length - 1);
234
235 // If there's no duplicate entry name, we should only overlap in the head or tail block. Try to
236 // trim both blocks. Skip this source chunk in case it still overlaps with the used ranges.
237 if (AlignHead(start, length) && !used_ranges.Overlaps(*start, *length)) {
238 return true;
239 }
240 if (AlignTail(start, length) && !used_ranges.Overlaps(*start, *length)) {
241 return true;
242 }
243
244 printf("Failed to remove the overlapped block ranges; skip the source\n");
245 return false;
246}
247
248static const struct option OPTIONS[] = {
249 { "zip-mode", no_argument, nullptr, 'z' },
250 { "bonus-file", required_argument, nullptr, 'b' },
251 { "block-limit", required_argument, nullptr, 0 },
252 { "debug-dir", required_argument, nullptr, 0 },
Tianjie Xu82582b42017-08-31 18:05:19 -0700253 { "split-info", required_argument, nullptr, 0 },
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700254 { nullptr, 0, nullptr, 0 },
255};
256
Tianjie Xu57dd9612017-08-17 17:50:56 -0700257ImageChunk::ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content,
258 size_t raw_data_len, std::string entry_name)
259 : type_(type),
260 start_(start),
261 input_file_ptr_(file_content),
262 raw_data_len_(raw_data_len),
263 compress_level_(6),
264 entry_name_(std::move(entry_name)) {
265 CHECK(file_content != nullptr) << "input file container can't be nullptr";
266}
Doug Zongker512536a2010-02-17 16:11:44 -0800267
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800268const uint8_t* ImageChunk::GetRawData() const {
269 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
270 return input_file_ptr_->data() + start_;
271}
272
273const uint8_t * ImageChunk::DataForPatch() const {
274 if (type_ == CHUNK_DEFLATE) {
275 return uncompressed_data_.data();
276 }
277 return GetRawData();
278}
279
280size_t ImageChunk::DataLengthForPatch() const {
281 if (type_ == CHUNK_DEFLATE) {
282 return uncompressed_data_.size();
283 }
284 return raw_data_len_;
285}
286
287bool ImageChunk::operator==(const ImageChunk& other) const {
288 if (type_ != other.type_) {
289 return false;
290 }
291 return (raw_data_len_ == other.raw_data_len_ &&
292 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
293}
294
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800295void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800296 uncompressed_data_ = std::move(data);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800297}
298
299bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
300 if (type_ != CHUNK_DEFLATE) {
301 return false;
302 }
303 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
304 return true;
305}
306
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800307void ImageChunk::ChangeDeflateChunkToNormal() {
308 if (type_ != CHUNK_DEFLATE) return;
309 type_ = CHUNK_NORMAL;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700310 // No need to clear the entry name.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800311 uncompressed_data_.clear();
312}
313
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800314bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
315 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
316 return false;
317 }
318 return (other.start_ == start_ + raw_data_len_);
319}
320
321void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
322 CHECK(IsAdjacentNormal(other));
323 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
324}
325
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700326bool ImageChunk::MakePatch(const ImageChunk& tgt, const ImageChunk& src,
Alex Deymofa188262017-10-10 17:56:17 +0200327 std::vector<uint8_t>* patch_data,
328 bsdiff::SuffixArrayIndexInterface** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700329#if defined(__ANDROID__)
330 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
331#else
332 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
333#endif
334
335 int fd = mkstemp(ptemp);
336 if (fd == -1) {
337 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
338 return false;
339 }
340 close(fd);
341
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700342 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
343 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700344 if (r != 0) {
345 printf("bsdiff() failed: %d\n", r);
346 return false;
347 }
348
349 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
350 if (patch_fd == -1) {
351 printf("failed to open %s: %s\n", ptemp, strerror(errno));
352 return false;
353 }
354 struct stat st;
355 if (fstat(patch_fd, &st) != 0) {
356 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
357 return false;
358 }
359
360 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700361
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700362 patch_data->resize(sz);
363 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
364 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
365 unlink(ptemp);
366 return false;
367 }
368
369 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700370
371 return true;
372}
373
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800374bool ImageChunk::ReconstructDeflateChunk() {
375 if (type_ != CHUNK_DEFLATE) {
376 printf("attempt to reconstruct non-deflate chunk\n");
377 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800378 }
379
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700380 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
381 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800382 for (int level = 6; level <= 9; level += 3) {
383 if (TryReconstruction(level)) {
384 compress_level_ = level;
385 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800386 }
387 }
Doug Zongker512536a2010-02-17 16:11:44 -0800388
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800389 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800390}
391
392/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700393 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
394 * in the chunk, and checks that it matches exactly the compressed data we started with (also
395 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800396 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800397bool ImageChunk::TryReconstruction(int level) {
398 z_stream strm;
399 strm.zalloc = Z_NULL;
400 strm.zfree = Z_NULL;
401 strm.opaque = Z_NULL;
402 strm.avail_in = uncompressed_data_.size();
403 strm.next_in = uncompressed_data_.data();
404 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
405 if (ret < 0) {
406 printf("failed to initialize deflate: %d\n", ret);
407 return false;
408 }
409
410 std::vector<uint8_t> buffer(BUFFER_SIZE);
411 size_t offset = 0;
412 do {
413 strm.avail_out = buffer.size();
414 strm.next_out = buffer.data();
415 ret = deflate(&strm, Z_FINISH);
416 if (ret < 0) {
417 printf("failed to deflate: %d\n", ret);
418 return false;
419 }
420
421 size_t compressed_size = buffer.size() - strm.avail_out;
422 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
423 // mismatch; data isn't the same.
424 deflateEnd(&strm);
425 return false;
426 }
427 offset += compressed_size;
428 } while (ret != Z_STREAM_END);
429 deflateEnd(&strm);
430
431 if (offset != raw_data_len_) {
432 // mismatch; ran out of data before we should have.
433 return false;
434 }
435 return true;
436}
437
Tianjie Xu57dd9612017-08-17 17:50:56 -0700438PatchChunk::PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
439 : type_(tgt.GetType()),
440 source_start_(src.GetStartOffset()),
441 source_len_(src.GetRawDataLength()),
442 source_uncompressed_len_(src.DataLengthForPatch()),
443 target_start_(tgt.GetStartOffset()),
444 target_len_(tgt.GetRawDataLength()),
445 target_uncompressed_len_(tgt.DataLengthForPatch()),
446 target_compress_level_(tgt.GetCompressLevel()),
447 data_(std::move(data)) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700448
Tianjie Xu57dd9612017-08-17 17:50:56 -0700449// Construct a CHUNK_RAW patch from the target data directly.
450PatchChunk::PatchChunk(const ImageChunk& tgt)
451 : type_(CHUNK_RAW),
452 source_start_(0),
453 source_len_(0),
454 source_uncompressed_len_(0),
455 target_start_(tgt.GetStartOffset()),
456 target_len_(tgt.GetRawDataLength()),
457 target_uncompressed_len_(tgt.DataLengthForPatch()),
458 target_compress_level_(tgt.GetCompressLevel()),
459 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700460
461// Return true if raw data is smaller than the patch size.
462bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
463 size_t target_len = tgt.GetRawDataLength();
464 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
465}
466
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700467void PatchChunk::UpdateSourceOffset(const SortedRangeSet& src_range) {
468 if (type_ == CHUNK_DEFLATE) {
469 source_start_ = src_range.GetOffsetInRangeSet(source_start_);
470 }
471}
472
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700473// Header size:
474// header_type 4 bytes
475// CHUNK_NORMAL 8*3 = 24 bytes
476// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
477// CHUNK_RAW 4 bytes + patch_size
478size_t PatchChunk::GetHeaderSize() const {
479 switch (type_) {
480 case CHUNK_NORMAL:
481 return 4 + 8 * 3;
482 case CHUNK_DEFLATE:
483 return 4 + 8 * 5 + 4 * 5;
484 case CHUNK_RAW:
485 return 4 + 4 + data_.size();
486 default:
487 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
488 return 0;
489 }
490}
491
492// Return the offset of the next patch into the patch data.
493size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
494 Write4(fd, type_);
495 switch (type_) {
496 case CHUNK_NORMAL:
497 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
498 Write8(fd, static_cast<int64_t>(source_start_));
499 Write8(fd, static_cast<int64_t>(source_len_));
500 Write8(fd, static_cast<int64_t>(offset));
501 return offset + data_.size();
502 case CHUNK_DEFLATE:
503 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
504 Write8(fd, static_cast<int64_t>(source_start_));
505 Write8(fd, static_cast<int64_t>(source_len_));
506 Write8(fd, static_cast<int64_t>(offset));
507 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
508 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
509 Write4(fd, target_compress_level_);
510 Write4(fd, ImageChunk::METHOD);
511 Write4(fd, ImageChunk::WINDOWBITS);
512 Write4(fd, ImageChunk::MEMLEVEL);
513 Write4(fd, ImageChunk::STRATEGY);
514 return offset + data_.size();
515 case CHUNK_RAW:
516 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
517 Write4(fd, static_cast<int32_t>(data_.size()));
518 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
519 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
520 }
521 return offset;
522 default:
523 CHECK(false) << "unexpected chunk type: " << type_;
524 return offset;
525 }
526}
527
Tianjie Xu82582b42017-08-31 18:05:19 -0700528size_t PatchChunk::PatchSize() const {
529 if (type_ == CHUNK_RAW) {
530 return GetHeaderSize();
531 }
532 return GetHeaderSize() + data_.size();
533}
534
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700535// Write the contents of |patch_chunks| to |patch_fd|.
536bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
537 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
538 // the offset of each bsdiff patch within the file.
539 size_t total_header_size = 12;
540 for (const auto& patch : patch_chunks) {
541 total_header_size += patch.GetHeaderSize();
542 }
543
544 size_t offset = total_header_size;
545
546 // Write out the headers.
Tianjie Xu82582b42017-08-31 18:05:19 -0700547 if (!android::base::WriteStringToFd("IMGDIFF" + std::to_string(VERSION), patch_fd)) {
548 printf("failed to write \"IMGDIFF%zu\": %s\n", VERSION, strerror(errno));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700549 return false;
550 }
551
552 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
553 for (size_t i = 0; i < patch_chunks.size(); ++i) {
554 printf("chunk %zu: ", i);
555 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
556 }
557
558 // Append each chunk's bsdiff patch, in order.
559 for (const auto& patch : patch_chunks) {
560 if (patch.type_ == CHUNK_RAW) {
561 continue;
562 }
563 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
564 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
565 return false;
566 }
567 }
568
569 return true;
570}
571
Tianjie Xu57dd9612017-08-17 17:50:56 -0700572ImageChunk& Image::operator[](size_t i) {
573 CHECK_LT(i, chunks_.size());
574 return chunks_[i];
575}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700576
Tianjie Xu57dd9612017-08-17 17:50:56 -0700577const ImageChunk& Image::operator[](size_t i) const {
578 CHECK_LT(i, chunks_.size());
579 return chunks_[i];
580}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700581
582void Image::MergeAdjacentNormalChunks() {
583 size_t merged_last = 0, cur = 0;
584 while (cur < chunks_.size()) {
585 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
586 // length of the current normal chunk.
587 size_t to_check = cur + 1;
588 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
589 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
590 to_check++;
591 }
592
593 if (merged_last != cur) {
594 chunks_[merged_last] = std::move(chunks_[cur]);
595 }
596 merged_last++;
597 cur = to_check;
598 }
599 if (merged_last < chunks_.size()) {
600 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
601 }
602}
603
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700604void Image::DumpChunks() const {
605 std::string type = is_source_ ? "source" : "target";
606 printf("Dumping chunks for %s\n", type.c_str());
607 for (size_t i = 0; i < chunks_.size(); ++i) {
608 printf("chunk %zu: ", i);
609 chunks_[i].Dump();
610 }
611}
612
613bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
614 CHECK(file_content != nullptr);
615
616 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
617 if (fd == -1) {
618 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
619 return false;
620 }
621 struct stat st;
622 if (fstat(fd, &st) != 0) {
623 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
624 return false;
625 }
626
627 size_t sz = static_cast<size_t>(st.st_size);
628 file_content->resize(sz);
629 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
630 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
631 return false;
632 }
633 fd.reset();
634
635 return true;
636}
637
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700638bool ZipModeImage::Initialize(const std::string& filename) {
639 if (!ReadFile(filename, &file_content_)) {
640 return false;
641 }
642
643 // Omit the trailing zeros before we pass the file to ziparchive handler.
644 size_t zipfile_size;
645 if (!GetZipFileSize(&zipfile_size)) {
646 printf("failed to parse the actual size of %s\n", filename.c_str());
647 return false;
648 }
649 ZipArchiveHandle handle;
650 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
651 filename.c_str(), &handle);
652 if (err != 0) {
653 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
654 CloseArchive(handle);
655 return false;
656 }
657
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700658 if (!InitializeChunks(filename, handle)) {
659 CloseArchive(handle);
660 return false;
661 }
662
663 CloseArchive(handle);
664 return true;
665}
666
667// Iterate the zip entries and compose the image chunks accordingly.
668bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
669 void* cookie;
670 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
671 if (ret != 0) {
672 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
673 return false;
674 }
675
676 // Create a list of deflated zip entries, sorted by offset.
677 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
678 ZipString name;
679 ZipEntry entry;
680 while ((ret = Next(cookie, &entry, &name)) == 0) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700681 if (entry.method == kCompressDeflated || limit_ > 0) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700682 std::string entry_name(name.name, name.name + name.name_length);
683 temp_entries.emplace_back(entry_name, entry);
684 }
685 }
686
687 if (ret != -1) {
688 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
689 return false;
690 }
691 std::sort(temp_entries.begin(), temp_entries.end(),
692 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
693
694 EndIteration(cookie);
695
696 // For source chunks, we don't need to compose chunks for the metadata.
697 if (is_source_) {
698 for (auto& entry : temp_entries) {
699 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
700 printf("Failed to add %s to source chunks\n", entry.first.c_str());
701 return false;
702 }
703 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700704
705 // Add the end of zip file (mainly central directory) as a normal chunk.
706 size_t entries_end = 0;
707 if (!temp_entries.empty()) {
708 entries_end = static_cast<size_t>(temp_entries.back().second.offset +
709 temp_entries.back().second.compressed_length);
710 }
711 CHECK_LT(entries_end, file_content_.size());
712 chunks_.emplace_back(CHUNK_NORMAL, entries_end, &file_content_,
713 file_content_.size() - entries_end);
714
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700715 return true;
716 }
717
718 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
719 // deflate entries as CHUNK_NORMAL.
720 size_t pos = 0;
721 size_t nextentry = 0;
722 while (pos < file_content_.size()) {
723 if (nextentry < temp_entries.size() &&
724 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
725 // Add the next zip entry.
726 std::string entry_name = temp_entries[nextentry].first;
727 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
728 printf("Failed to add %s to target chunks\n", entry_name.c_str());
729 return false;
730 }
731
732 pos += temp_entries[nextentry].second.compressed_length;
733 ++nextentry;
734 continue;
735 }
736
737 // Use a normal chunk to take all the data up to the start of the next entry.
738 size_t raw_data_len;
739 if (nextentry < temp_entries.size()) {
740 raw_data_len = temp_entries[nextentry].second.offset - pos;
741 } else {
742 raw_data_len = file_content_.size() - pos;
743 }
744 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
745
746 pos += raw_data_len;
747 }
748
749 return true;
750}
751
752bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
753 ZipEntry* entry) {
754 size_t compressed_len = entry->compressed_length;
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700755 if (compressed_len == 0) return true;
756
757 // Split the entry into several normal chunks if it's too large.
758 if (limit_ > 0 && compressed_len > limit_) {
759 int count = 0;
760 while (compressed_len > 0) {
761 size_t length = std::min(limit_, compressed_len);
762 std::string name = entry_name + "-" + std::to_string(count);
763 chunks_.emplace_back(CHUNK_NORMAL, entry->offset + limit_ * count, &file_content_, length,
764 name);
765
766 count++;
767 compressed_len -= length;
768 }
769 } else if (entry->method == kCompressDeflated) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700770 size_t uncompressed_len = entry->uncompressed_length;
771 std::vector<uint8_t> uncompressed_data(uncompressed_len);
772 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
773 if (ret != 0) {
774 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
775 ErrorCodeString(ret));
776 return false;
777 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700778 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700779 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700780 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700781 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700782 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700783 }
784
785 return true;
786}
787
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800788// EOCD record
789// offset 0: signature 0x06054b50, 4 bytes
790// offset 4: number of this disk, 2 bytes
791// ...
792// offset 20: comment length, 2 bytes
793// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700794bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
795 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800796 printf("file is too small to be a zip file\n");
797 return false;
798 }
799
800 // Look for End of central directory record of the zip file, and calculate the actual
801 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700802 for (int i = file_content_.size() - 22; i >= 0; i--) {
803 if (file_content_[i] == 0x50) {
804 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800805 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700806 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800807
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700808 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800809 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700810 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800811 *input_file_size = file_size;
812 return true;
813 }
814 }
815 }
816
817 // EOCD not found, this file is likely not a valid zip file.
818 return false;
819}
820
Tianjie Xu57dd9612017-08-17 17:50:56 -0700821ImageChunk ZipModeImage::PseudoSource() const {
822 CHECK(is_source_);
823 return ImageChunk(CHUNK_NORMAL, 0, &file_content_, file_content_.size());
824}
825
826const ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) const {
827 if (name.empty()) {
828 return nullptr;
829 }
830 for (auto& chunk : chunks_) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700831 if (chunk.GetType() != CHUNK_DEFLATE && !find_normal) {
832 continue;
833 }
834
835 if (chunk.GetEntryName() == name) {
Tianjie Xu57dd9612017-08-17 17:50:56 -0700836 return &chunk;
837 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700838
839 // Edge case when target chunk is split due to size limit but source chunk isn't.
840 if (name == (chunk.GetEntryName() + "-0") || chunk.GetEntryName() == (name + "-0")) {
841 return &chunk;
842 }
843
844 // TODO handle the .so files with incremental version number.
845 // (e.g. lib/arm64-v8a/libcronet.59.0.3050.4.so)
Tianjie Xu57dd9612017-08-17 17:50:56 -0700846 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700847
Tianjie Xu57dd9612017-08-17 17:50:56 -0700848 return nullptr;
849}
850
851ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) {
852 return const_cast<ImageChunk*>(
853 static_cast<const ZipModeImage*>(this)->FindChunkByName(name, find_normal));
854}
855
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700856bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
857 for (auto& tgt_chunk : *tgt_image) {
858 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800859 continue;
860 }
861
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700862 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
863 if (src_chunk == nullptr) {
864 tgt_chunk.ChangeDeflateChunkToNormal();
865 } else if (tgt_chunk == *src_chunk) {
866 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
867 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
868 // patch to the compressed data, rather than uncompressing and recompressing to apply the
869 // trivial patch to the uncompressed data.
870 tgt_chunk.ChangeDeflateChunkToNormal();
871 src_chunk->ChangeDeflateChunkToNormal();
872 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
873 // We cannot recompress the data and get exactly the same bits as are in the input target
874 // image. Treat the chunk as a normal non-deflated chunk.
875 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
876 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800877
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700878 tgt_chunk.ChangeDeflateChunkToNormal();
879 src_chunk->ChangeDeflateChunkToNormal();
880 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800881 }
882
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700883 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
884 // filename, and normal chunks are patched using the entire source file as the source.
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700885 if (tgt_image->limit_ == 0) {
886 tgt_image->MergeAdjacentNormalChunks();
887 tgt_image->DumpChunks();
888 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800889
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700890 return true;
891}
892
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700893// For each target chunk, look for the corresponding source chunk by the zip_entry name. If
894// found, add the range of this chunk in the original source file to the block aligned source
895// ranges. Construct the split src & tgt image once the size of source range reaches limit.
896bool ZipModeImage::SplitZipModeImageWithLimit(const ZipModeImage& tgt_image,
897 const ZipModeImage& src_image,
898 std::vector<ZipModeImage>* split_tgt_images,
899 std::vector<ZipModeImage>* split_src_images,
900 std::vector<SortedRangeSet>* split_src_ranges) {
901 CHECK_EQ(tgt_image.limit_, src_image.limit_);
902 size_t limit = tgt_image.limit_;
903
904 src_image.DumpChunks();
905 printf("Splitting %zu tgt chunks...\n", tgt_image.NumOfChunks());
906
907 SortedRangeSet used_src_ranges; // ranges used for previous split source images.
908
909 // Reserve the central directory in advance for the last split image.
910 const auto& central_directory = src_image.cend() - 1;
911 CHECK_EQ(CHUNK_NORMAL, central_directory->GetType());
912 used_src_ranges.Insert(central_directory->GetStartOffset(),
913 central_directory->DataLengthForPatch());
914
915 SortedRangeSet src_ranges;
916 std::vector<ImageChunk> split_src_chunks;
917 std::vector<ImageChunk> split_tgt_chunks;
918 for (auto tgt = tgt_image.cbegin(); tgt != tgt_image.cend(); tgt++) {
919 const ImageChunk* src = src_image.FindChunkByName(tgt->GetEntryName(), true);
920 if (src == nullptr) {
921 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
922 tgt->GetRawDataLength());
923 continue;
924 }
925
926 size_t src_offset = src->GetStartOffset();
927 size_t src_length = src->GetRawDataLength();
928
929 CHECK(src_length > 0);
930 CHECK_LE(src_length, limit);
931
932 // Make sure this source range hasn't been used before so that the src_range pieces don't
933 // overlap with each other.
934 if (!RemoveUsedBlocks(&src_offset, &src_length, used_src_ranges)) {
935 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
936 tgt->GetRawDataLength());
937 } else if (src_ranges.blocks() * BLOCK_SIZE + src_length <= limit) {
938 src_ranges.Insert(src_offset, src_length);
939
940 // Add the deflate source chunk if it hasn't been aligned.
941 if (src->GetType() == CHUNK_DEFLATE && src_length == src->GetRawDataLength()) {
942 split_src_chunks.push_back(*src);
943 split_tgt_chunks.push_back(*tgt);
944 } else {
945 // TODO split smarter to avoid alignment of large deflate chunks
946 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
947 tgt->GetRawDataLength());
948 }
949 } else {
950 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
951 split_src_chunks, split_tgt_images,
952 split_src_images);
953
954 split_tgt_chunks.clear();
955 split_src_chunks.clear();
956 used_src_ranges.Insert(src_ranges);
957 split_src_ranges->push_back(std::move(src_ranges));
958 src_ranges.Clear();
959
960 // We don't have enough space for the current chunk; start a new split image and handle
961 // this chunk there.
962 tgt--;
963 }
964 }
965
966 // TODO Trim it in case the CD exceeds limit too much.
967 src_ranges.Insert(central_directory->GetStartOffset(), central_directory->DataLengthForPatch());
968 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
969 split_src_chunks, split_tgt_images, split_src_images);
970 split_src_ranges->push_back(std::move(src_ranges));
971
972 ValidateSplitImages(*split_tgt_images, *split_src_images, *split_src_ranges,
973 tgt_image.file_content_.size());
974
975 return true;
976}
977
978void ZipModeImage::AddSplitImageFromChunkList(const ZipModeImage& tgt_image,
979 const ZipModeImage& src_image,
980 const SortedRangeSet& split_src_ranges,
981 const std::vector<ImageChunk>& split_tgt_chunks,
982 const std::vector<ImageChunk>& split_src_chunks,
983 std::vector<ZipModeImage>* split_tgt_images,
984 std::vector<ZipModeImage>* split_src_images) {
985 CHECK(!split_tgt_chunks.empty());
986 // Target chunks should occupy at least one block.
987 // TODO put a warning and change the type to raw if it happens in extremely rare cases.
988 size_t tgt_size = split_tgt_chunks.back().GetStartOffset() +
989 split_tgt_chunks.back().DataLengthForPatch() -
990 split_tgt_chunks.front().GetStartOffset();
991 CHECK_GE(tgt_size, BLOCK_SIZE);
992
993 std::vector<ImageChunk> aligned_tgt_chunks;
994
995 // Align the target chunks in the beginning with BLOCK_SIZE.
996 size_t i = 0;
997 while (i < split_tgt_chunks.size()) {
998 size_t tgt_start = split_tgt_chunks[i].GetStartOffset();
999 size_t tgt_length = split_tgt_chunks[i].GetRawDataLength();
1000
1001 // Current ImageChunk is long enough to align.
1002 if (AlignHead(&tgt_start, &tgt_length)) {
1003 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt_start, &tgt_image.file_content_,
1004 tgt_length);
1005 break;
1006 }
1007
1008 i++;
1009 }
1010 CHECK_LT(i, split_tgt_chunks.size());
1011 aligned_tgt_chunks.insert(aligned_tgt_chunks.end(), split_tgt_chunks.begin() + i + 1,
1012 split_tgt_chunks.end());
1013 CHECK(!aligned_tgt_chunks.empty());
1014
1015 // Add a normal chunk to align the contents in the end.
1016 size_t end_offset =
1017 aligned_tgt_chunks.back().GetStartOffset() + aligned_tgt_chunks.back().GetRawDataLength();
1018 if (end_offset % BLOCK_SIZE != 0 && end_offset < tgt_image.file_content_.size()) {
1019 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, end_offset, &tgt_image.file_content_,
1020 BLOCK_SIZE - (end_offset % BLOCK_SIZE));
1021 }
1022
1023 ZipModeImage split_tgt_image(false);
1024 split_tgt_image.Initialize(std::move(aligned_tgt_chunks), {});
1025 split_tgt_image.MergeAdjacentNormalChunks();
1026
1027 // Construct the dummy source file based on the src_ranges.
1028 std::vector<uint8_t> src_content;
1029 for (const auto& r : split_src_ranges) {
1030 size_t end = std::min(src_image.file_content_.size(), r.second * BLOCK_SIZE);
1031 src_content.insert(src_content.end(), src_image.file_content_.begin() + r.first * BLOCK_SIZE,
1032 src_image.file_content_.begin() + end);
1033 }
1034
1035 // We should not have an empty src in our design; otherwise we will encounter an error in
1036 // bsdiff since src_content.data() == nullptr.
1037 CHECK(!src_content.empty());
1038
1039 ZipModeImage split_src_image(true);
1040 split_src_image.Initialize(split_src_chunks, std::move(src_content));
1041
1042 split_tgt_images->push_back(std::move(split_tgt_image));
1043 split_src_images->push_back(std::move(split_src_image));
1044}
1045
1046void ZipModeImage::ValidateSplitImages(const std::vector<ZipModeImage>& split_tgt_images,
1047 const std::vector<ZipModeImage>& split_src_images,
1048 std::vector<SortedRangeSet>& split_src_ranges,
1049 size_t total_tgt_size) {
1050 CHECK_EQ(split_tgt_images.size(), split_src_images.size());
1051
1052 printf("Validating %zu images\n", split_tgt_images.size());
1053
1054 // Verify that the target image pieces is continuous and can add up to the total size.
1055 size_t last_offset = 0;
1056 for (const auto& tgt_image : split_tgt_images) {
1057 CHECK(!tgt_image.chunks_.empty());
1058
1059 CHECK_EQ(last_offset, tgt_image.chunks_.front().GetStartOffset());
1060 CHECK(last_offset % BLOCK_SIZE == 0);
1061
1062 // Check the target chunks within the split image are continuous.
1063 for (const auto& chunk : tgt_image.chunks_) {
1064 CHECK_EQ(last_offset, chunk.GetStartOffset());
1065 last_offset += chunk.GetRawDataLength();
1066 }
1067 }
1068 CHECK_EQ(total_tgt_size, last_offset);
1069
1070 // Verify that the source ranges are mutually exclusive.
1071 CHECK_EQ(split_src_images.size(), split_src_ranges.size());
1072 SortedRangeSet used_src_ranges;
1073 for (size_t i = 0; i < split_src_ranges.size(); i++) {
1074 CHECK(!used_src_ranges.Overlaps(split_src_ranges[i]))
1075 << "src range " << split_src_ranges[i].ToString() << " overlaps "
1076 << used_src_ranges.ToString();
1077 used_src_ranges.Insert(split_src_ranges[i]);
1078 }
1079}
1080
1081bool ZipModeImage::GeneratePatchesInternal(const ZipModeImage& tgt_image,
1082 const ZipModeImage& src_image,
1083 std::vector<PatchChunk>* patch_chunks) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001084 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001085 patch_chunks->clear();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001086
Alex Deymofa188262017-10-10 17:56:17 +02001087 bsdiff::SuffixArrayIndexInterface* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001088 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1089 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001090
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001091 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001092 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001093 continue;
1094 }
1095
1096 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
1097 ? nullptr
1098 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
1099
1100 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Alex Deymofa188262017-10-10 17:56:17 +02001101 bsdiff::SuffixArrayIndexInterface** bsdiff_cache_ptr =
1102 (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001103
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001104 std::vector<uint8_t> patch_data;
1105 if (!ImageChunk::MakePatch(tgt_chunk, src_ref, &patch_data, bsdiff_cache_ptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001106 printf("Failed to generate patch, name: %s\n", tgt_chunk.GetEntryName().c_str());
1107 return false;
1108 }
1109
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001110 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001111 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001112
1113 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001114 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001115 } else {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001116 patch_chunks->emplace_back(tgt_chunk, src_ref, std::move(patch_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001117 }
Tianjie Xu12b90552017-03-07 14:44:14 -08001118 }
Alex Deymofa188262017-10-10 17:56:17 +02001119 delete bsdiff_cache;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001120
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001121 CHECK_EQ(patch_chunks->size(), tgt_image.NumOfChunks());
1122 return true;
1123}
1124
1125bool ZipModeImage::GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
1126 const std::string& patch_name) {
1127 std::vector<PatchChunk> patch_chunks;
1128
1129 ZipModeImage::GeneratePatchesInternal(tgt_image, src_image, &patch_chunks);
1130
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001131 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1132
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001133 android::base::unique_fd patch_fd(
1134 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1135 if (patch_fd == -1) {
1136 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001137 return false;
1138 }
1139
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001140 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001141}
1142
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001143bool ZipModeImage::GeneratePatches(const std::vector<ZipModeImage>& split_tgt_images,
1144 const std::vector<ZipModeImage>& split_src_images,
1145 const std::vector<SortedRangeSet>& split_src_ranges,
Tianjie Xu82582b42017-08-31 18:05:19 -07001146 const std::string& patch_name,
1147 const std::string& split_info_file,
1148 const std::string& debug_dir) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001149 printf("Construct patches for %zu split images...\n", split_tgt_images.size());
1150
1151 android::base::unique_fd patch_fd(
1152 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1153 if (patch_fd == -1) {
1154 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1155 return false;
1156 }
1157
Tianjie Xu82582b42017-08-31 18:05:19 -07001158 std::vector<std::string> split_info_list;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001159 for (size_t i = 0; i < split_tgt_images.size(); i++) {
1160 std::vector<PatchChunk> patch_chunks;
1161 if (!ZipModeImage::GeneratePatchesInternal(split_tgt_images[i], split_src_images[i],
1162 &patch_chunks)) {
1163 printf("failed to generate split patch\n");
1164 return false;
1165 }
1166
Tianjie Xu82582b42017-08-31 18:05:19 -07001167 size_t total_patch_size = 12;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001168 for (auto& p : patch_chunks) {
1169 p.UpdateSourceOffset(split_src_ranges[i]);
Tianjie Xu82582b42017-08-31 18:05:19 -07001170 total_patch_size += p.PatchSize();
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001171 }
1172
1173 if (!PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd)) {
1174 return false;
1175 }
1176
Tianjie Xu82582b42017-08-31 18:05:19 -07001177 size_t split_tgt_size = split_tgt_images[i].chunks_.back().GetStartOffset() +
1178 split_tgt_images[i].chunks_.back().GetRawDataLength() -
1179 split_tgt_images[i].chunks_.front().GetStartOffset();
1180 std::string split_info = android::base::StringPrintf(
1181 "%zu %zu %s", total_patch_size, split_tgt_size, split_src_ranges[i].ToString().c_str());
1182 split_info_list.push_back(split_info);
1183
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001184 // Write the split source & patch into the debug directory.
1185 if (!debug_dir.empty()) {
1186 std::string src_name = android::base::StringPrintf("%s/src-%zu", debug_dir.c_str(), i);
1187 android::base::unique_fd fd(
1188 open(src_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1189
1190 if (fd == -1) {
1191 printf("Failed to open %s\n", src_name.c_str());
1192 return false;
1193 }
1194 if (!android::base::WriteFully(fd, split_src_images[i].PseudoSource().DataForPatch(),
1195 split_src_images[i].PseudoSource().DataLengthForPatch())) {
1196 printf("Failed to write split source data into %s\n", src_name.c_str());
1197 return false;
1198 }
1199
1200 std::string patch_name = android::base::StringPrintf("%s/patch-%zu", debug_dir.c_str(), i);
1201 fd.reset(open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1202
1203 if (fd == -1) {
1204 printf("Failed to open %s\n", patch_name.c_str());
1205 return false;
1206 }
1207 if (!PatchChunk::WritePatchDataToFd(patch_chunks, fd)) {
1208 return false;
1209 }
1210 }
1211 }
Tianjie Xu82582b42017-08-31 18:05:19 -07001212
1213 // Store the split in the following format:
1214 // Line 0: imgdiff version#
1215 // Line 1: number of pieces
1216 // Line 2: patch_size_1 tgt_size_1 src_range_1
1217 // ...
1218 // Line n+1: patch_size_n tgt_size_n src_range_n
1219 std::string split_info_string = android::base::StringPrintf(
1220 "%zu\n%zu\n", VERSION, split_info_list.size()) + android::base::Join(split_info_list, '\n');
1221 if (!android::base::WriteStringToFile(split_info_string, split_info_file)) {
1222 printf("failed to write split info to \"%s\": %s\n", split_info_file.c_str(),
1223 strerror(errno));
1224 return false;
1225 }
1226
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001227 return true;
1228}
1229
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001230bool ImageModeImage::Initialize(const std::string& filename) {
1231 if (!ReadFile(filename, &file_content_)) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001232 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001233 }
Doug Zongker512536a2010-02-17 16:11:44 -08001234
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001235 size_t sz = file_content_.size();
Doug Zongker512536a2010-02-17 16:11:44 -08001236 size_t pos = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -07001237 while (pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001238 // 0x00 no header flags, 0x08 deflate compression, 0x1f8b gzip magic number
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001239 if (sz - pos >= 4 && get_unaligned<uint32_t>(file_content_.data() + pos) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001240 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +02001241 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001242
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001243 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
1244 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001245 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, sz - pos);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001246 break;
1247 }
Doug Zongker512536a2010-02-17 16:11:44 -08001248
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001249 // We need three chunks for the deflated image in total, one normal chunk for the header,
1250 // one deflated chunk for the body, and another normal chunk for the footer.
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001251 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_HEADER_LEN);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001252 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001253
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001254 // We must decompress this chunk in order to discover where it ends, and so we can update
1255 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -08001256
1257 z_stream strm;
1258 strm.zalloc = Z_NULL;
1259 strm.zfree = Z_NULL;
1260 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -07001261 strm.avail_in = sz - pos;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001262 strm.next_in = file_content_.data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001263
1264 // -15 means we are decoding a 'raw' deflate stream; zlib will
1265 // not expect zlib headers.
1266 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001267 if (ret < 0) {
1268 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001269 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001270 }
Doug Zongker512536a2010-02-17 16:11:44 -08001271
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001272 size_t allocated = BUFFER_SIZE;
1273 std::vector<uint8_t> uncompressed_data(allocated);
1274 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001275 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001276 strm.avail_out = allocated - uncompressed_len;
1277 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001278 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +02001279 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001280 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -08001281 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001282 break;
Johan Redestigc68bd342015-04-14 21:20:06 +02001283 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001284 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -08001285 if (strm.avail_out == 0) {
1286 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001287 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -08001288 }
1289 } while (ret != Z_STREAM_END);
1290
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001291 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001292 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001293
1294 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001295 continue;
1296 }
1297
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001298 // The footer contains the size of the uncompressed data. Double-check to make sure that it
1299 // matches the size of the data we got when we actually did the decompression.
1300 size_t footer_index = pos + raw_data_len + GZIP_FOOTER_LEN - 4;
1301 if (sz - footer_index < 4) {
1302 printf("Warning: invalid footer position; treating as a nomal chunk\n");
1303 continue;
1304 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001305 size_t footer_size = get_unaligned<uint32_t>(file_content_.data() + footer_index);
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001306 if (footer_size != uncompressed_len) {
1307 printf("Warning: footer size %zu != decompressed size %zu; treating as a nomal chunk\n",
1308 footer_size, uncompressed_len);
1309 continue;
1310 }
1311
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001312 ImageChunk body(CHUNK_DEFLATE, pos, &file_content_, raw_data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001313 uncompressed_data.resize(uncompressed_len);
1314 body.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001315 chunks_.push_back(std::move(body));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001316
1317 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001318
1319 // create a normal chunk for the footer
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001320 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -08001321
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001322 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001323 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001324 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
1325 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -08001326
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001327 // Scan forward until we find a gzip header.
1328 size_t data_len = 0;
1329 while (data_len + pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001330 if (data_len + pos + 4 <= sz &&
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001331 get_unaligned<uint32_t>(file_content_.data() + pos + data_len) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001332 break;
1333 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001334 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -08001335 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001336 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001337
1338 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001339 }
1340 }
1341
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001342 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001343}
1344
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001345bool ImageModeImage::SetBonusData(const std::vector<uint8_t>& bonus_data) {
1346 CHECK(is_source_);
1347 if (chunks_.size() < 2 || !chunks_[1].SetBonusData(bonus_data)) {
1348 printf("Failed to set bonus data\n");
1349 DumpChunks();
1350 return false;
1351 }
1352
1353 printf(" using %zu bytes of bonus data\n", bonus_data.size());
1354 return true;
1355}
1356
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001357// In Image Mode, verify that the source and target images have the same chunk structure (ie, the
1358// same sequence of deflate and normal chunks).
1359bool ImageModeImage::CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image) {
1360 // In image mode, merge the gzip header and footer in with any adjacent normal chunks.
1361 tgt_image->MergeAdjacentNormalChunks();
1362 src_image->MergeAdjacentNormalChunks();
Doug Zongker512536a2010-02-17 16:11:44 -08001363
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001364 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1365 printf("source and target don't have same number of chunks!\n");
1366 tgt_image->DumpChunks();
1367 src_image->DumpChunks();
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001368 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +02001369 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001370 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001371 if ((*tgt_image)[i].GetType() != (*src_image)[i].GetType()) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001372 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
1373 tgt_image->DumpChunks();
1374 src_image->DumpChunks();
1375 return false;
1376 }
Doug Zongker512536a2010-02-17 16:11:44 -08001377 }
1378
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001379 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001380 auto& tgt_chunk = (*tgt_image)[i];
1381 auto& src_chunk = (*src_image)[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001382 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
1383 continue;
1384 }
1385
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001386 // If two deflate chunks are identical treat them as normal chunks.
1387 if (tgt_chunk == src_chunk) {
1388 tgt_chunk.ChangeDeflateChunkToNormal();
1389 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001390 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
1391 // We cannot recompress the data and get exactly the same bits as are in the input target
1392 // image, fall back to normal
1393 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
1394 tgt_chunk.GetEntryName().c_str());
1395 tgt_chunk.ChangeDeflateChunkToNormal();
1396 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001397 }
Doug Zongker512536a2010-02-17 16:11:44 -08001398 }
1399
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001400 // For images, we need to maintain the parallel structure of the chunk lists, so do the merging
1401 // in both the source and target lists.
1402 tgt_image->MergeAdjacentNormalChunks();
1403 src_image->MergeAdjacentNormalChunks();
1404 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1405 // This shouldn't happen.
1406 printf("merging normal chunks went awry\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001407 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001408 }
Doug Zongker512536a2010-02-17 16:11:44 -08001409
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001410 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001411}
1412
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001413// In image mode, generate patches against the given source chunks and bonus_data; write the
1414// result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001415bool ImageModeImage::GeneratePatches(const ImageModeImage& tgt_image,
1416 const ImageModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001417 const std::string& patch_name) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001418 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
1419 std::vector<PatchChunk> patch_chunks;
1420 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001421
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001422 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1423 const auto& tgt_chunk = tgt_image[i];
1424 const auto& src_chunk = src_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001425
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001426 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
1427 patch_chunks.emplace_back(tgt_chunk);
1428 continue;
Doug Zongker512536a2010-02-17 16:11:44 -08001429 }
1430
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001431 std::vector<uint8_t> patch_data;
1432 if (!ImageChunk::MakePatch(tgt_chunk, src_chunk, &patch_data, nullptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001433 printf("Failed to generate patch for target chunk %zu: ", i);
1434 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001435 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001436 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001437 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001438
1439 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
1440 patch_chunks.emplace_back(tgt_chunk);
1441 } else {
1442 patch_chunks.emplace_back(tgt_chunk, src_chunk, std::move(patch_data));
1443 }
Doug Zongker512536a2010-02-17 16:11:44 -08001444 }
Doug Zongker512536a2010-02-17 16:11:44 -08001445
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001446 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1447
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001448 android::base::unique_fd patch_fd(
1449 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1450 if (patch_fd == -1) {
1451 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1452 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001453 }
Doug Zongker512536a2010-02-17 16:11:44 -08001454
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001455 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Doug Zongker512536a2010-02-17 16:11:44 -08001456}
1457
Tao Bao97555da2016-12-15 10:15:06 -08001458int imgdiff(int argc, const char** argv) {
1459 bool zip_mode = false;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001460 std::vector<uint8_t> bonus_data;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001461 size_t blocks_limit = 0;
Tianjie Xu82582b42017-08-31 18:05:19 -07001462 std::string split_info_file;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001463 std::string debug_dir;
Tianjie Xu12b90552017-03-07 14:44:14 -08001464
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001465 int opt;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001466 int option_index;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001467 optind = 1; // Reset the getopt state so that we can call it multiple times for test.
Doug Zongkera3ccba62012-08-20 15:28:02 -07001468
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001469 while ((opt = getopt_long(argc, const_cast<char**>(argv), "zb:", OPTIONS, &option_index)) != -1) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001470 switch (opt) {
1471 case 'z':
1472 zip_mode = true;
1473 break;
1474 case 'b': {
1475 android::base::unique_fd fd(open(optarg, O_RDONLY));
1476 if (fd == -1) {
1477 printf("failed to open bonus file %s: %s\n", optarg, strerror(errno));
1478 return 1;
1479 }
1480 struct stat st;
1481 if (fstat(fd, &st) != 0) {
1482 printf("failed to stat bonus file %s: %s\n", optarg, strerror(errno));
1483 return 1;
1484 }
1485
1486 size_t bonus_size = st.st_size;
1487 bonus_data.resize(bonus_size);
1488 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
1489 printf("failed to read bonus file %s: %s\n", optarg, strerror(errno));
1490 return 1;
1491 }
1492 break;
1493 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001494 case 0: {
1495 std::string name = OPTIONS[option_index].name;
1496 if (name == "block-limit" && !android::base::ParseUint(optarg, &blocks_limit)) {
1497 printf("failed to parse size blocks_limit: %s\n", optarg);
1498 return 1;
Tianjie Xu82582b42017-08-31 18:05:19 -07001499 } else if (name == "split-info") {
1500 split_info_file = optarg;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001501 } else if (name == "debug-dir") {
1502 debug_dir = optarg;
1503 }
1504 break;
1505 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001506 default:
1507 printf("unexpected opt: %s\n", optarg);
1508 return 2;
1509 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001510 }
1511
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001512 if (argc - optind != 3) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001513 printf("usage: %s [options] <src-img> <tgt-img> <patch-file>\n", argv[0]);
1514 printf(
1515 " -z <zip-mode>, Generate patches in zip mode, src and tgt should be zip files.\n"
1516 " -b <bonus-file>, Bonus file in addition to src, image mode only.\n"
1517 " --block-limit, For large zips, split the src and tgt based on the block limit;\n"
1518 " and generate patches between each pair of pieces. Concatenate these\n"
1519 " patches together and output them into <patch-file>.\n"
Tianjie Xu82582b42017-08-31 18:05:19 -07001520 " --split-info, Output the split information (patch_size, tgt_size, src_ranges);\n"
1521 " zip mode with block-limit only.\n"
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001522 " --debug_dir, Debug directory to put the split srcs and patches, zip mode only.\n");
Doug Zongkera3ccba62012-08-20 15:28:02 -07001523 return 2;
1524 }
Doug Zongker512536a2010-02-17 16:11:44 -08001525
Doug Zongker512536a2010-02-17 16:11:44 -08001526 if (zip_mode) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001527 ZipModeImage src_image(true, blocks_limit * BLOCK_SIZE);
1528 ZipModeImage tgt_image(false, blocks_limit * BLOCK_SIZE);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001529
1530 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001531 return 1;
1532 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001533 if (!tgt_image.Initialize(argv[optind + 1])) {
1534 return 1;
1535 }
1536
1537 if (!ZipModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
1538 return 1;
1539 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001540
1541 // TODO save and output the split information so that caller can create split transfer lists
1542 // accordingly.
1543
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001544 // Compute bsdiff patches for each chunk's data (the uncompressed data, in the case of
1545 // deflate chunks).
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001546 if (blocks_limit > 0) {
Tianjie Xu82582b42017-08-31 18:05:19 -07001547 if (split_info_file.empty()) {
1548 printf("split-info path cannot be empty when generating patches with a block-limit.\n");
1549 return 1;
1550 }
1551
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001552 std::vector<ZipModeImage> split_tgt_images;
1553 std::vector<ZipModeImage> split_src_images;
1554 std::vector<SortedRangeSet> split_src_ranges;
1555 ZipModeImage::SplitZipModeImageWithLimit(tgt_image, src_image, &split_tgt_images,
1556 &split_src_images, &split_src_ranges);
1557
1558 if (!ZipModeImage::GeneratePatches(split_tgt_images, split_src_images, split_src_ranges,
Tianjie Xu82582b42017-08-31 18:05:19 -07001559 argv[optind + 2], split_info_file, debug_dir)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001560 return 1;
1561 }
1562
1563 } else if (!ZipModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001564 return 1;
1565 }
1566 } else {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001567 ImageModeImage src_image(true);
1568 ImageModeImage tgt_image(false);
1569
1570 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001571 return 1;
1572 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001573 if (!tgt_image.Initialize(argv[optind + 1])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001574 return 1;
1575 }
1576
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001577 if (!ImageModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
Doug Zongker512536a2010-02-17 16:11:44 -08001578 return 1;
1579 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001580
1581 if (!bonus_data.empty() && !src_image.SetBonusData(bonus_data)) {
1582 return 1;
1583 }
1584
1585 if (!ImageModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001586 return 1;
1587 }
1588 }
1589
Doug Zongker512536a2010-02-17 16:11:44 -08001590 return 0;
1591}