blob: 69ad75f3718b37e0bdb8d34aa541ae4a49088994 [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>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700166#include <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,
327 std::vector<uint8_t>* patch_data, saidx_t** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700328#if defined(__ANDROID__)
329 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
330#else
331 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
332#endif
333
334 int fd = mkstemp(ptemp);
335 if (fd == -1) {
336 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
337 return false;
338 }
339 close(fd);
340
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700341 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
342 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700343 if (r != 0) {
344 printf("bsdiff() failed: %d\n", r);
345 return false;
346 }
347
348 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
349 if (patch_fd == -1) {
350 printf("failed to open %s: %s\n", ptemp, strerror(errno));
351 return false;
352 }
353 struct stat st;
354 if (fstat(patch_fd, &st) != 0) {
355 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
356 return false;
357 }
358
359 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700360
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700361 patch_data->resize(sz);
362 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
363 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
364 unlink(ptemp);
365 return false;
366 }
367
368 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700369
370 return true;
371}
372
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800373bool ImageChunk::ReconstructDeflateChunk() {
374 if (type_ != CHUNK_DEFLATE) {
375 printf("attempt to reconstruct non-deflate chunk\n");
376 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800377 }
378
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700379 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
380 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800381 for (int level = 6; level <= 9; level += 3) {
382 if (TryReconstruction(level)) {
383 compress_level_ = level;
384 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800385 }
386 }
Doug Zongker512536a2010-02-17 16:11:44 -0800387
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800388 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800389}
390
391/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700392 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
393 * in the chunk, and checks that it matches exactly the compressed data we started with (also
394 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800395 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800396bool ImageChunk::TryReconstruction(int level) {
397 z_stream strm;
398 strm.zalloc = Z_NULL;
399 strm.zfree = Z_NULL;
400 strm.opaque = Z_NULL;
401 strm.avail_in = uncompressed_data_.size();
402 strm.next_in = uncompressed_data_.data();
403 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
404 if (ret < 0) {
405 printf("failed to initialize deflate: %d\n", ret);
406 return false;
407 }
408
409 std::vector<uint8_t> buffer(BUFFER_SIZE);
410 size_t offset = 0;
411 do {
412 strm.avail_out = buffer.size();
413 strm.next_out = buffer.data();
414 ret = deflate(&strm, Z_FINISH);
415 if (ret < 0) {
416 printf("failed to deflate: %d\n", ret);
417 return false;
418 }
419
420 size_t compressed_size = buffer.size() - strm.avail_out;
421 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
422 // mismatch; data isn't the same.
423 deflateEnd(&strm);
424 return false;
425 }
426 offset += compressed_size;
427 } while (ret != Z_STREAM_END);
428 deflateEnd(&strm);
429
430 if (offset != raw_data_len_) {
431 // mismatch; ran out of data before we should have.
432 return false;
433 }
434 return true;
435}
436
Tianjie Xu57dd9612017-08-17 17:50:56 -0700437PatchChunk::PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
438 : type_(tgt.GetType()),
439 source_start_(src.GetStartOffset()),
440 source_len_(src.GetRawDataLength()),
441 source_uncompressed_len_(src.DataLengthForPatch()),
442 target_start_(tgt.GetStartOffset()),
443 target_len_(tgt.GetRawDataLength()),
444 target_uncompressed_len_(tgt.DataLengthForPatch()),
445 target_compress_level_(tgt.GetCompressLevel()),
446 data_(std::move(data)) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700447
Tianjie Xu57dd9612017-08-17 17:50:56 -0700448// Construct a CHUNK_RAW patch from the target data directly.
449PatchChunk::PatchChunk(const ImageChunk& tgt)
450 : type_(CHUNK_RAW),
451 source_start_(0),
452 source_len_(0),
453 source_uncompressed_len_(0),
454 target_start_(tgt.GetStartOffset()),
455 target_len_(tgt.GetRawDataLength()),
456 target_uncompressed_len_(tgt.DataLengthForPatch()),
457 target_compress_level_(tgt.GetCompressLevel()),
458 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700459
460// Return true if raw data is smaller than the patch size.
461bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
462 size_t target_len = tgt.GetRawDataLength();
463 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
464}
465
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700466void PatchChunk::UpdateSourceOffset(const SortedRangeSet& src_range) {
467 if (type_ == CHUNK_DEFLATE) {
468 source_start_ = src_range.GetOffsetInRangeSet(source_start_);
469 }
470}
471
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700472// Header size:
473// header_type 4 bytes
474// CHUNK_NORMAL 8*3 = 24 bytes
475// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
476// CHUNK_RAW 4 bytes + patch_size
477size_t PatchChunk::GetHeaderSize() const {
478 switch (type_) {
479 case CHUNK_NORMAL:
480 return 4 + 8 * 3;
481 case CHUNK_DEFLATE:
482 return 4 + 8 * 5 + 4 * 5;
483 case CHUNK_RAW:
484 return 4 + 4 + data_.size();
485 default:
486 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
487 return 0;
488 }
489}
490
491// Return the offset of the next patch into the patch data.
492size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
493 Write4(fd, type_);
494 switch (type_) {
495 case CHUNK_NORMAL:
496 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
497 Write8(fd, static_cast<int64_t>(source_start_));
498 Write8(fd, static_cast<int64_t>(source_len_));
499 Write8(fd, static_cast<int64_t>(offset));
500 return offset + data_.size();
501 case CHUNK_DEFLATE:
502 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
503 Write8(fd, static_cast<int64_t>(source_start_));
504 Write8(fd, static_cast<int64_t>(source_len_));
505 Write8(fd, static_cast<int64_t>(offset));
506 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
507 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
508 Write4(fd, target_compress_level_);
509 Write4(fd, ImageChunk::METHOD);
510 Write4(fd, ImageChunk::WINDOWBITS);
511 Write4(fd, ImageChunk::MEMLEVEL);
512 Write4(fd, ImageChunk::STRATEGY);
513 return offset + data_.size();
514 case CHUNK_RAW:
515 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
516 Write4(fd, static_cast<int32_t>(data_.size()));
517 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
518 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
519 }
520 return offset;
521 default:
522 CHECK(false) << "unexpected chunk type: " << type_;
523 return offset;
524 }
525}
526
Tianjie Xu82582b42017-08-31 18:05:19 -0700527size_t PatchChunk::PatchSize() const {
528 if (type_ == CHUNK_RAW) {
529 return GetHeaderSize();
530 }
531 return GetHeaderSize() + data_.size();
532}
533
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700534// Write the contents of |patch_chunks| to |patch_fd|.
535bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
536 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
537 // the offset of each bsdiff patch within the file.
538 size_t total_header_size = 12;
539 for (const auto& patch : patch_chunks) {
540 total_header_size += patch.GetHeaderSize();
541 }
542
543 size_t offset = total_header_size;
544
545 // Write out the headers.
Tianjie Xu82582b42017-08-31 18:05:19 -0700546 if (!android::base::WriteStringToFd("IMGDIFF" + std::to_string(VERSION), patch_fd)) {
547 printf("failed to write \"IMGDIFF%zu\": %s\n", VERSION, strerror(errno));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700548 return false;
549 }
550
551 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
552 for (size_t i = 0; i < patch_chunks.size(); ++i) {
553 printf("chunk %zu: ", i);
554 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
555 }
556
557 // Append each chunk's bsdiff patch, in order.
558 for (const auto& patch : patch_chunks) {
559 if (patch.type_ == CHUNK_RAW) {
560 continue;
561 }
562 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
563 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
564 return false;
565 }
566 }
567
568 return true;
569}
570
Tianjie Xu57dd9612017-08-17 17:50:56 -0700571ImageChunk& Image::operator[](size_t i) {
572 CHECK_LT(i, chunks_.size());
573 return chunks_[i];
574}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700575
Tianjie Xu57dd9612017-08-17 17:50:56 -0700576const ImageChunk& Image::operator[](size_t i) const {
577 CHECK_LT(i, chunks_.size());
578 return chunks_[i];
579}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700580
581void Image::MergeAdjacentNormalChunks() {
582 size_t merged_last = 0, cur = 0;
583 while (cur < chunks_.size()) {
584 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
585 // length of the current normal chunk.
586 size_t to_check = cur + 1;
587 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
588 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
589 to_check++;
590 }
591
592 if (merged_last != cur) {
593 chunks_[merged_last] = std::move(chunks_[cur]);
594 }
595 merged_last++;
596 cur = to_check;
597 }
598 if (merged_last < chunks_.size()) {
599 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
600 }
601}
602
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700603void Image::DumpChunks() const {
604 std::string type = is_source_ ? "source" : "target";
605 printf("Dumping chunks for %s\n", type.c_str());
606 for (size_t i = 0; i < chunks_.size(); ++i) {
607 printf("chunk %zu: ", i);
608 chunks_[i].Dump();
609 }
610}
611
612bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
613 CHECK(file_content != nullptr);
614
615 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
616 if (fd == -1) {
617 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
618 return false;
619 }
620 struct stat st;
621 if (fstat(fd, &st) != 0) {
622 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
623 return false;
624 }
625
626 size_t sz = static_cast<size_t>(st.st_size);
627 file_content->resize(sz);
628 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
629 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
630 return false;
631 }
632 fd.reset();
633
634 return true;
635}
636
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700637bool ZipModeImage::Initialize(const std::string& filename) {
638 if (!ReadFile(filename, &file_content_)) {
639 return false;
640 }
641
642 // Omit the trailing zeros before we pass the file to ziparchive handler.
643 size_t zipfile_size;
644 if (!GetZipFileSize(&zipfile_size)) {
645 printf("failed to parse the actual size of %s\n", filename.c_str());
646 return false;
647 }
648 ZipArchiveHandle handle;
649 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
650 filename.c_str(), &handle);
651 if (err != 0) {
652 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
653 CloseArchive(handle);
654 return false;
655 }
656
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700657 if (!InitializeChunks(filename, handle)) {
658 CloseArchive(handle);
659 return false;
660 }
661
662 CloseArchive(handle);
663 return true;
664}
665
666// Iterate the zip entries and compose the image chunks accordingly.
667bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
668 void* cookie;
669 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
670 if (ret != 0) {
671 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
672 return false;
673 }
674
675 // Create a list of deflated zip entries, sorted by offset.
676 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
677 ZipString name;
678 ZipEntry entry;
679 while ((ret = Next(cookie, &entry, &name)) == 0) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700680 if (entry.method == kCompressDeflated || limit_ > 0) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700681 std::string entry_name(name.name, name.name + name.name_length);
682 temp_entries.emplace_back(entry_name, entry);
683 }
684 }
685
686 if (ret != -1) {
687 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
688 return false;
689 }
690 std::sort(temp_entries.begin(), temp_entries.end(),
691 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
692
693 EndIteration(cookie);
694
695 // For source chunks, we don't need to compose chunks for the metadata.
696 if (is_source_) {
697 for (auto& entry : temp_entries) {
698 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
699 printf("Failed to add %s to source chunks\n", entry.first.c_str());
700 return false;
701 }
702 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700703
704 // Add the end of zip file (mainly central directory) as a normal chunk.
705 size_t entries_end = 0;
706 if (!temp_entries.empty()) {
707 entries_end = static_cast<size_t>(temp_entries.back().second.offset +
708 temp_entries.back().second.compressed_length);
709 }
710 CHECK_LT(entries_end, file_content_.size());
711 chunks_.emplace_back(CHUNK_NORMAL, entries_end, &file_content_,
712 file_content_.size() - entries_end);
713
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700714 return true;
715 }
716
717 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
718 // deflate entries as CHUNK_NORMAL.
719 size_t pos = 0;
720 size_t nextentry = 0;
721 while (pos < file_content_.size()) {
722 if (nextentry < temp_entries.size() &&
723 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
724 // Add the next zip entry.
725 std::string entry_name = temp_entries[nextentry].first;
726 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
727 printf("Failed to add %s to target chunks\n", entry_name.c_str());
728 return false;
729 }
730
731 pos += temp_entries[nextentry].second.compressed_length;
732 ++nextentry;
733 continue;
734 }
735
736 // Use a normal chunk to take all the data up to the start of the next entry.
737 size_t raw_data_len;
738 if (nextentry < temp_entries.size()) {
739 raw_data_len = temp_entries[nextentry].second.offset - pos;
740 } else {
741 raw_data_len = file_content_.size() - pos;
742 }
743 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
744
745 pos += raw_data_len;
746 }
747
748 return true;
749}
750
751bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
752 ZipEntry* entry) {
753 size_t compressed_len = entry->compressed_length;
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700754 if (compressed_len == 0) return true;
755
756 // Split the entry into several normal chunks if it's too large.
757 if (limit_ > 0 && compressed_len > limit_) {
758 int count = 0;
759 while (compressed_len > 0) {
760 size_t length = std::min(limit_, compressed_len);
761 std::string name = entry_name + "-" + std::to_string(count);
762 chunks_.emplace_back(CHUNK_NORMAL, entry->offset + limit_ * count, &file_content_, length,
763 name);
764
765 count++;
766 compressed_len -= length;
767 }
768 } else if (entry->method == kCompressDeflated) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700769 size_t uncompressed_len = entry->uncompressed_length;
770 std::vector<uint8_t> uncompressed_data(uncompressed_len);
771 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
772 if (ret != 0) {
773 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
774 ErrorCodeString(ret));
775 return false;
776 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700777 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700778 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700779 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700780 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700781 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700782 }
783
784 return true;
785}
786
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800787// EOCD record
788// offset 0: signature 0x06054b50, 4 bytes
789// offset 4: number of this disk, 2 bytes
790// ...
791// offset 20: comment length, 2 bytes
792// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700793bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
794 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800795 printf("file is too small to be a zip file\n");
796 return false;
797 }
798
799 // Look for End of central directory record of the zip file, and calculate the actual
800 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700801 for (int i = file_content_.size() - 22; i >= 0; i--) {
802 if (file_content_[i] == 0x50) {
803 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800804 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700805 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800806
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700807 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800808 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700809 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800810 *input_file_size = file_size;
811 return true;
812 }
813 }
814 }
815
816 // EOCD not found, this file is likely not a valid zip file.
817 return false;
818}
819
Tianjie Xu57dd9612017-08-17 17:50:56 -0700820ImageChunk ZipModeImage::PseudoSource() const {
821 CHECK(is_source_);
822 return ImageChunk(CHUNK_NORMAL, 0, &file_content_, file_content_.size());
823}
824
825const ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) const {
826 if (name.empty()) {
827 return nullptr;
828 }
829 for (auto& chunk : chunks_) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700830 if (chunk.GetType() != CHUNK_DEFLATE && !find_normal) {
831 continue;
832 }
833
834 if (chunk.GetEntryName() == name) {
Tianjie Xu57dd9612017-08-17 17:50:56 -0700835 return &chunk;
836 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700837
838 // Edge case when target chunk is split due to size limit but source chunk isn't.
839 if (name == (chunk.GetEntryName() + "-0") || chunk.GetEntryName() == (name + "-0")) {
840 return &chunk;
841 }
842
843 // TODO handle the .so files with incremental version number.
844 // (e.g. lib/arm64-v8a/libcronet.59.0.3050.4.so)
Tianjie Xu57dd9612017-08-17 17:50:56 -0700845 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700846
Tianjie Xu57dd9612017-08-17 17:50:56 -0700847 return nullptr;
848}
849
850ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) {
851 return const_cast<ImageChunk*>(
852 static_cast<const ZipModeImage*>(this)->FindChunkByName(name, find_normal));
853}
854
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700855bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
856 for (auto& tgt_chunk : *tgt_image) {
857 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800858 continue;
859 }
860
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700861 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
862 if (src_chunk == nullptr) {
863 tgt_chunk.ChangeDeflateChunkToNormal();
864 } else if (tgt_chunk == *src_chunk) {
865 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
866 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
867 // patch to the compressed data, rather than uncompressing and recompressing to apply the
868 // trivial patch to the uncompressed data.
869 tgt_chunk.ChangeDeflateChunkToNormal();
870 src_chunk->ChangeDeflateChunkToNormal();
871 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
872 // We cannot recompress the data and get exactly the same bits as are in the input target
873 // image. Treat the chunk as a normal non-deflated chunk.
874 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
875 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800876
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700877 tgt_chunk.ChangeDeflateChunkToNormal();
878 src_chunk->ChangeDeflateChunkToNormal();
879 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800880 }
881
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700882 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
883 // filename, and normal chunks are patched using the entire source file as the source.
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700884 if (tgt_image->limit_ == 0) {
885 tgt_image->MergeAdjacentNormalChunks();
886 tgt_image->DumpChunks();
887 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800888
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700889 return true;
890}
891
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700892// For each target chunk, look for the corresponding source chunk by the zip_entry name. If
893// found, add the range of this chunk in the original source file to the block aligned source
894// ranges. Construct the split src & tgt image once the size of source range reaches limit.
895bool ZipModeImage::SplitZipModeImageWithLimit(const ZipModeImage& tgt_image,
896 const ZipModeImage& src_image,
897 std::vector<ZipModeImage>* split_tgt_images,
898 std::vector<ZipModeImage>* split_src_images,
899 std::vector<SortedRangeSet>* split_src_ranges) {
900 CHECK_EQ(tgt_image.limit_, src_image.limit_);
901 size_t limit = tgt_image.limit_;
902
903 src_image.DumpChunks();
904 printf("Splitting %zu tgt chunks...\n", tgt_image.NumOfChunks());
905
906 SortedRangeSet used_src_ranges; // ranges used for previous split source images.
907
908 // Reserve the central directory in advance for the last split image.
909 const auto& central_directory = src_image.cend() - 1;
910 CHECK_EQ(CHUNK_NORMAL, central_directory->GetType());
911 used_src_ranges.Insert(central_directory->GetStartOffset(),
912 central_directory->DataLengthForPatch());
913
914 SortedRangeSet src_ranges;
915 std::vector<ImageChunk> split_src_chunks;
916 std::vector<ImageChunk> split_tgt_chunks;
917 for (auto tgt = tgt_image.cbegin(); tgt != tgt_image.cend(); tgt++) {
918 const ImageChunk* src = src_image.FindChunkByName(tgt->GetEntryName(), true);
919 if (src == nullptr) {
920 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
921 tgt->GetRawDataLength());
922 continue;
923 }
924
925 size_t src_offset = src->GetStartOffset();
926 size_t src_length = src->GetRawDataLength();
927
928 CHECK(src_length > 0);
929 CHECK_LE(src_length, limit);
930
931 // Make sure this source range hasn't been used before so that the src_range pieces don't
932 // overlap with each other.
933 if (!RemoveUsedBlocks(&src_offset, &src_length, used_src_ranges)) {
934 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
935 tgt->GetRawDataLength());
936 } else if (src_ranges.blocks() * BLOCK_SIZE + src_length <= limit) {
937 src_ranges.Insert(src_offset, src_length);
938
939 // Add the deflate source chunk if it hasn't been aligned.
940 if (src->GetType() == CHUNK_DEFLATE && src_length == src->GetRawDataLength()) {
941 split_src_chunks.push_back(*src);
942 split_tgt_chunks.push_back(*tgt);
943 } else {
944 // TODO split smarter to avoid alignment of large deflate chunks
945 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
946 tgt->GetRawDataLength());
947 }
948 } else {
949 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
950 split_src_chunks, split_tgt_images,
951 split_src_images);
952
953 split_tgt_chunks.clear();
954 split_src_chunks.clear();
955 used_src_ranges.Insert(src_ranges);
956 split_src_ranges->push_back(std::move(src_ranges));
957 src_ranges.Clear();
958
959 // We don't have enough space for the current chunk; start a new split image and handle
960 // this chunk there.
961 tgt--;
962 }
963 }
964
965 // TODO Trim it in case the CD exceeds limit too much.
966 src_ranges.Insert(central_directory->GetStartOffset(), central_directory->DataLengthForPatch());
967 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
968 split_src_chunks, split_tgt_images, split_src_images);
969 split_src_ranges->push_back(std::move(src_ranges));
970
971 ValidateSplitImages(*split_tgt_images, *split_src_images, *split_src_ranges,
972 tgt_image.file_content_.size());
973
974 return true;
975}
976
977void ZipModeImage::AddSplitImageFromChunkList(const ZipModeImage& tgt_image,
978 const ZipModeImage& src_image,
979 const SortedRangeSet& split_src_ranges,
980 const std::vector<ImageChunk>& split_tgt_chunks,
981 const std::vector<ImageChunk>& split_src_chunks,
982 std::vector<ZipModeImage>* split_tgt_images,
983 std::vector<ZipModeImage>* split_src_images) {
984 CHECK(!split_tgt_chunks.empty());
985 // Target chunks should occupy at least one block.
986 // TODO put a warning and change the type to raw if it happens in extremely rare cases.
987 size_t tgt_size = split_tgt_chunks.back().GetStartOffset() +
988 split_tgt_chunks.back().DataLengthForPatch() -
989 split_tgt_chunks.front().GetStartOffset();
990 CHECK_GE(tgt_size, BLOCK_SIZE);
991
992 std::vector<ImageChunk> aligned_tgt_chunks;
993
994 // Align the target chunks in the beginning with BLOCK_SIZE.
995 size_t i = 0;
996 while (i < split_tgt_chunks.size()) {
997 size_t tgt_start = split_tgt_chunks[i].GetStartOffset();
998 size_t tgt_length = split_tgt_chunks[i].GetRawDataLength();
999
1000 // Current ImageChunk is long enough to align.
1001 if (AlignHead(&tgt_start, &tgt_length)) {
1002 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt_start, &tgt_image.file_content_,
1003 tgt_length);
1004 break;
1005 }
1006
1007 i++;
1008 }
1009 CHECK_LT(i, split_tgt_chunks.size());
1010 aligned_tgt_chunks.insert(aligned_tgt_chunks.end(), split_tgt_chunks.begin() + i + 1,
1011 split_tgt_chunks.end());
1012 CHECK(!aligned_tgt_chunks.empty());
1013
1014 // Add a normal chunk to align the contents in the end.
1015 size_t end_offset =
1016 aligned_tgt_chunks.back().GetStartOffset() + aligned_tgt_chunks.back().GetRawDataLength();
1017 if (end_offset % BLOCK_SIZE != 0 && end_offset < tgt_image.file_content_.size()) {
1018 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, end_offset, &tgt_image.file_content_,
1019 BLOCK_SIZE - (end_offset % BLOCK_SIZE));
1020 }
1021
1022 ZipModeImage split_tgt_image(false);
1023 split_tgt_image.Initialize(std::move(aligned_tgt_chunks), {});
1024 split_tgt_image.MergeAdjacentNormalChunks();
1025
1026 // Construct the dummy source file based on the src_ranges.
1027 std::vector<uint8_t> src_content;
1028 for (const auto& r : split_src_ranges) {
1029 size_t end = std::min(src_image.file_content_.size(), r.second * BLOCK_SIZE);
1030 src_content.insert(src_content.end(), src_image.file_content_.begin() + r.first * BLOCK_SIZE,
1031 src_image.file_content_.begin() + end);
1032 }
1033
1034 // We should not have an empty src in our design; otherwise we will encounter an error in
1035 // bsdiff since src_content.data() == nullptr.
1036 CHECK(!src_content.empty());
1037
1038 ZipModeImage split_src_image(true);
1039 split_src_image.Initialize(split_src_chunks, std::move(src_content));
1040
1041 split_tgt_images->push_back(std::move(split_tgt_image));
1042 split_src_images->push_back(std::move(split_src_image));
1043}
1044
1045void ZipModeImage::ValidateSplitImages(const std::vector<ZipModeImage>& split_tgt_images,
1046 const std::vector<ZipModeImage>& split_src_images,
1047 std::vector<SortedRangeSet>& split_src_ranges,
1048 size_t total_tgt_size) {
1049 CHECK_EQ(split_tgt_images.size(), split_src_images.size());
1050
1051 printf("Validating %zu images\n", split_tgt_images.size());
1052
1053 // Verify that the target image pieces is continuous and can add up to the total size.
1054 size_t last_offset = 0;
1055 for (const auto& tgt_image : split_tgt_images) {
1056 CHECK(!tgt_image.chunks_.empty());
1057
1058 CHECK_EQ(last_offset, tgt_image.chunks_.front().GetStartOffset());
1059 CHECK(last_offset % BLOCK_SIZE == 0);
1060
1061 // Check the target chunks within the split image are continuous.
1062 for (const auto& chunk : tgt_image.chunks_) {
1063 CHECK_EQ(last_offset, chunk.GetStartOffset());
1064 last_offset += chunk.GetRawDataLength();
1065 }
1066 }
1067 CHECK_EQ(total_tgt_size, last_offset);
1068
1069 // Verify that the source ranges are mutually exclusive.
1070 CHECK_EQ(split_src_images.size(), split_src_ranges.size());
1071 SortedRangeSet used_src_ranges;
1072 for (size_t i = 0; i < split_src_ranges.size(); i++) {
1073 CHECK(!used_src_ranges.Overlaps(split_src_ranges[i]))
1074 << "src range " << split_src_ranges[i].ToString() << " overlaps "
1075 << used_src_ranges.ToString();
1076 used_src_ranges.Insert(split_src_ranges[i]);
1077 }
1078}
1079
1080bool ZipModeImage::GeneratePatchesInternal(const ZipModeImage& tgt_image,
1081 const ZipModeImage& src_image,
1082 std::vector<PatchChunk>* patch_chunks) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001083 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001084 patch_chunks->clear();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001085
1086 saidx_t* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001087 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1088 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001089
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001090 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001091 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001092 continue;
1093 }
1094
1095 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
1096 ? nullptr
1097 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
1098
1099 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001100 saidx_t** bsdiff_cache_ptr = (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
1101
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 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001117 free(bsdiff_cache);
1118
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}