blob: 2eb618fbff02736943cfa378446789ba0a86f16b [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/*
18 * This program constructs binary patches for images -- such as boot.img
19 * and recovery.img -- that consist primarily of large chunks of gzipped
20 * data interspersed with uncompressed data. Doing a naive bsdiff of
21 * these files is not useful because small changes in the data lead to
22 * large changes in the compressed bitstream; bsdiff patches of gzipped
23 * data are typically as large as the data itself.
24 *
25 * To patch these usefully, we break the source and target images up into
26 * chunks of two types: "normal" and "gzip". Normal chunks are simply
27 * patched using a plain bsdiff. Gzip chunks are first expanded, then a
28 * bsdiff is applied to the uncompressed data, then the patched data is
29 * gzipped using the same encoder parameters. Patched chunks are
30 * concatenated together to create the output file; the output image
31 * should be *exactly* the same series of bytes as the target image used
32 * originally to generate the patch.
33 *
34 * To work well with this tool, the gzipped sections of the target
35 * image must have been generated using the same deflate encoder that
36 * is available in applypatch, namely, the one in the zlib library.
37 * In practice this means that images should be compressed using the
38 * "minigzip" tool included in the zlib distribution, not the GNU gzip
39 * program.
40 *
41 * An "imgdiff" patch consists of a header describing the chunk structure
42 * of the file and any encoding parameters needed for the gzipped
43 * chunks, followed by N bsdiff patches, one per chunk.
44 *
45 * For a diff to be generated, the source and target images must have the
46 * same "chunk" structure: that is, the same number of gzipped and normal
47 * chunks in the same order. Android boot and recovery images currently
48 * consist of five chunks: a small normal header, a gzipped kernel, a
49 * small normal section, a gzipped ramdisk, and finally a small normal
50 * footer.
51 *
52 * Caveats: we locate gzipped sections within the source and target
53 * images by searching for the byte sequence 1f8b0800: 1f8b is the gzip
54 * magic number; 08 specifies the "deflate" encoding [the only encoding
55 * supported by the gzip standard]; and 00 is the flags byte. We do not
56 * currently support any extra header fields (which would be indicated by
57 * a nonzero flags byte). We also don't handle the case when that byte
58 * sequence appears spuriously in the file. (Note that it would have to
59 * occur spuriously within a normal chunk to be a problem.)
60 *
61 *
62 * The imgdiff patch header looks like this:
63 *
64 * "IMGDIFF1" (8) [magic number and version]
65 * chunk count (4)
66 * for each chunk:
67 * chunk type (4) [CHUNK_{NORMAL, GZIP, DEFLATE, RAW}]
68 * if chunk type == CHUNK_NORMAL:
69 * source start (8)
70 * source len (8)
71 * bsdiff patch offset (8) [from start of patch file]
72 * if chunk type == CHUNK_GZIP: (version 1 only)
73 * source start (8)
74 * source len (8)
75 * bsdiff patch offset (8) [from start of patch file]
76 * source expanded len (8) [size of uncompressed source]
77 * target expected len (8) [size of uncompressed target]
78 * gzip level (4)
79 * method (4)
80 * windowBits (4)
81 * memLevel (4)
82 * strategy (4)
83 * gzip header len (4)
84 * gzip header (gzip header len)
85 * gzip footer (8)
86 * if chunk type == CHUNK_DEFLATE: (version 2 only)
87 * source start (8)
88 * source len (8)
89 * bsdiff patch offset (8) [from start of patch file]
90 * source expanded len (8) [size of uncompressed source]
91 * target expected len (8) [size of uncompressed target]
92 * gzip level (4)
93 * method (4)
94 * windowBits (4)
95 * memLevel (4)
96 * strategy (4)
97 * if chunk type == RAW: (version 2 only)
98 * target len (4)
99 * data (target len)
100 *
101 * All integers are little-endian. "source start" and "source len"
102 * specify the section of the input image that comprises this chunk,
103 * including the gzip header and footer for gzip chunks. "source
104 * expanded len" is the size of the uncompressed source data. "target
105 * expected len" is the size of the uncompressed data after applying
106 * the bsdiff patch. The next five parameters specify the zlib
107 * parameters to be used when compressing the patched data, and the
108 * next three specify the header and footer to be wrapped around the
109 * compressed data to create the output chunk (so that header contents
110 * like the timestamp are recreated exactly).
111 *
112 * After the header there are 'chunk count' bsdiff patches; the offset
113 * of each from the beginning of the file is specified in the header.
Doug Zongkera3ccba62012-08-20 15:28:02 -0700114 *
115 * This tool can take an optional file of "bonus data". This is an
116 * extra file of data that is appended to chunk #1 after it is
117 * compressed (it must be a CHUNK_DEFLATE chunk). The same file must
118 * be available (and passed to applypatch with -b) when applying the
119 * patch. This is used to reduce the size of recovery-from-boot
120 * patches by combining the boot image with recovery ramdisk
121 * information that is stored on the system partition.
Doug Zongker512536a2010-02-17 16:11:44 -0800122 */
123
Tao Bao97555da2016-12-15 10:15:06 -0800124#include "applypatch/imgdiff.h"
125
Doug Zongker512536a2010-02-17 16:11:44 -0800126#include <errno.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800127#include <fcntl.h>
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700128#include <getopt.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800129#include <stdio.h>
130#include <stdlib.h>
131#include <string.h>
132#include <sys/stat.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800133#include <sys/types.h>
Tao Bao97555da2016-12-15 10:15:06 -0800134#include <unistd.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800135
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800136#include <algorithm>
137#include <string>
138#include <vector>
139
Tao Baod37ce8f2016-12-17 17:10:04 -0800140#include <android-base/file.h>
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800141#include <android-base/logging.h>
142#include <android-base/memory.h>
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700143#include <android-base/parseint.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800144#include <android-base/unique_fd.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700145#include <bsdiff.h>
Tianjie Xu57dd9612017-08-17 17:50:56 -0700146#include <ziparchive/zip_archive.h>
Tao Bao97555da2016-12-15 10:15:06 -0800147#include <zlib.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700148
Tianjie Xu57dd9612017-08-17 17:50:56 -0700149#include "applypatch/imgdiff_image.h"
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700150#include "rangeset.h"
Tianjie Xu57dd9612017-08-17 17:50:56 -0700151
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800152using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800153
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700154static constexpr size_t BLOCK_SIZE = 4096;
155static constexpr size_t BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800156
Tianjie Xu12b90552017-03-07 14:44:14 -0800157// If we use this function to write the offset and length (type size_t), their values should not
158// exceed 2^63; because the signed bit will be casted away.
159static inline bool Write8(int fd, int64_t value) {
160 return android::base::WriteFully(fd, &value, sizeof(int64_t));
161}
162
163// Similarly, the value should not exceed 2^31 if we are casting from size_t (e.g. target chunk
164// size).
165static inline bool Write4(int fd, int32_t value) {
166 return android::base::WriteFully(fd, &value, sizeof(int32_t));
167}
168
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700169// Trim the head or tail to align with the block size. Return false if the chunk has nothing left
170// after alignment.
171static bool AlignHead(size_t* start, size_t* length) {
172 size_t residual = (*start % BLOCK_SIZE == 0) ? 0 : BLOCK_SIZE - *start % BLOCK_SIZE;
173
174 if (*length <= residual) {
175 *length = 0;
176 return false;
177 }
178
179 // Trim the data in the beginning.
180 *start += residual;
181 *length -= residual;
182 return true;
183}
184
185static bool AlignTail(size_t* start, size_t* length) {
186 size_t residual = (*start + *length) % BLOCK_SIZE;
187 if (*length <= residual) {
188 *length = 0;
189 return false;
190 }
191
192 // Trim the data in the end.
193 *length -= residual;
194 return true;
195}
196
197// Remove the used blocks from the source chunk to make sure the source ranges are mutually
198// exclusive after split. Return false if we fail to get the non-overlapped ranges. In such
199// a case, we'll skip the entire source chunk.
200static bool RemoveUsedBlocks(size_t* start, size_t* length, const SortedRangeSet& used_ranges) {
201 if (!used_ranges.Overlaps(*start, *length)) {
202 return true;
203 }
204
205 // TODO find the largest non-overlap chunk.
206 printf("Removing block %s from %zu - %zu\n", used_ranges.ToString().c_str(), *start,
207 *start + *length - 1);
208
209 // If there's no duplicate entry name, we should only overlap in the head or tail block. Try to
210 // trim both blocks. Skip this source chunk in case it still overlaps with the used ranges.
211 if (AlignHead(start, length) && !used_ranges.Overlaps(*start, *length)) {
212 return true;
213 }
214 if (AlignTail(start, length) && !used_ranges.Overlaps(*start, *length)) {
215 return true;
216 }
217
218 printf("Failed to remove the overlapped block ranges; skip the source\n");
219 return false;
220}
221
222static const struct option OPTIONS[] = {
223 { "zip-mode", no_argument, nullptr, 'z' },
224 { "bonus-file", required_argument, nullptr, 'b' },
225 { "block-limit", required_argument, nullptr, 0 },
226 { "debug-dir", required_argument, nullptr, 0 },
227 { nullptr, 0, nullptr, 0 },
228};
229
Tianjie Xu57dd9612017-08-17 17:50:56 -0700230ImageChunk::ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content,
231 size_t raw_data_len, std::string entry_name)
232 : type_(type),
233 start_(start),
234 input_file_ptr_(file_content),
235 raw_data_len_(raw_data_len),
236 compress_level_(6),
237 entry_name_(std::move(entry_name)) {
238 CHECK(file_content != nullptr) << "input file container can't be nullptr";
239}
Doug Zongker512536a2010-02-17 16:11:44 -0800240
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800241const uint8_t* ImageChunk::GetRawData() const {
242 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
243 return input_file_ptr_->data() + start_;
244}
245
246const uint8_t * ImageChunk::DataForPatch() const {
247 if (type_ == CHUNK_DEFLATE) {
248 return uncompressed_data_.data();
249 }
250 return GetRawData();
251}
252
253size_t ImageChunk::DataLengthForPatch() const {
254 if (type_ == CHUNK_DEFLATE) {
255 return uncompressed_data_.size();
256 }
257 return raw_data_len_;
258}
259
260bool ImageChunk::operator==(const ImageChunk& other) const {
261 if (type_ != other.type_) {
262 return false;
263 }
264 return (raw_data_len_ == other.raw_data_len_ &&
265 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
266}
267
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800268void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800269 uncompressed_data_ = std::move(data);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800270}
271
272bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
273 if (type_ != CHUNK_DEFLATE) {
274 return false;
275 }
276 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
277 return true;
278}
279
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800280void ImageChunk::ChangeDeflateChunkToNormal() {
281 if (type_ != CHUNK_DEFLATE) return;
282 type_ = CHUNK_NORMAL;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700283 // No need to clear the entry name.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800284 uncompressed_data_.clear();
285}
286
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800287bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
288 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
289 return false;
290 }
291 return (other.start_ == start_ + raw_data_len_);
292}
293
294void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
295 CHECK(IsAdjacentNormal(other));
296 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
297}
298
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700299bool ImageChunk::MakePatch(const ImageChunk& tgt, const ImageChunk& src,
300 std::vector<uint8_t>* patch_data, saidx_t** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700301#if defined(__ANDROID__)
302 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
303#else
304 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
305#endif
306
307 int fd = mkstemp(ptemp);
308 if (fd == -1) {
309 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
310 return false;
311 }
312 close(fd);
313
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700314 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
315 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700316 if (r != 0) {
317 printf("bsdiff() failed: %d\n", r);
318 return false;
319 }
320
321 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
322 if (patch_fd == -1) {
323 printf("failed to open %s: %s\n", ptemp, strerror(errno));
324 return false;
325 }
326 struct stat st;
327 if (fstat(patch_fd, &st) != 0) {
328 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
329 return false;
330 }
331
332 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700333
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700334 patch_data->resize(sz);
335 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
336 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
337 unlink(ptemp);
338 return false;
339 }
340
341 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700342
343 return true;
344}
345
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800346bool ImageChunk::ReconstructDeflateChunk() {
347 if (type_ != CHUNK_DEFLATE) {
348 printf("attempt to reconstruct non-deflate chunk\n");
349 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800350 }
351
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700352 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
353 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800354 for (int level = 6; level <= 9; level += 3) {
355 if (TryReconstruction(level)) {
356 compress_level_ = level;
357 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800358 }
359 }
Doug Zongker512536a2010-02-17 16:11:44 -0800360
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800361 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800362}
363
364/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700365 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
366 * in the chunk, and checks that it matches exactly the compressed data we started with (also
367 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800368 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800369bool ImageChunk::TryReconstruction(int level) {
370 z_stream strm;
371 strm.zalloc = Z_NULL;
372 strm.zfree = Z_NULL;
373 strm.opaque = Z_NULL;
374 strm.avail_in = uncompressed_data_.size();
375 strm.next_in = uncompressed_data_.data();
376 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
377 if (ret < 0) {
378 printf("failed to initialize deflate: %d\n", ret);
379 return false;
380 }
381
382 std::vector<uint8_t> buffer(BUFFER_SIZE);
383 size_t offset = 0;
384 do {
385 strm.avail_out = buffer.size();
386 strm.next_out = buffer.data();
387 ret = deflate(&strm, Z_FINISH);
388 if (ret < 0) {
389 printf("failed to deflate: %d\n", ret);
390 return false;
391 }
392
393 size_t compressed_size = buffer.size() - strm.avail_out;
394 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
395 // mismatch; data isn't the same.
396 deflateEnd(&strm);
397 return false;
398 }
399 offset += compressed_size;
400 } while (ret != Z_STREAM_END);
401 deflateEnd(&strm);
402
403 if (offset != raw_data_len_) {
404 // mismatch; ran out of data before we should have.
405 return false;
406 }
407 return true;
408}
409
Tianjie Xu57dd9612017-08-17 17:50:56 -0700410PatchChunk::PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
411 : type_(tgt.GetType()),
412 source_start_(src.GetStartOffset()),
413 source_len_(src.GetRawDataLength()),
414 source_uncompressed_len_(src.DataLengthForPatch()),
415 target_start_(tgt.GetStartOffset()),
416 target_len_(tgt.GetRawDataLength()),
417 target_uncompressed_len_(tgt.DataLengthForPatch()),
418 target_compress_level_(tgt.GetCompressLevel()),
419 data_(std::move(data)) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700420
Tianjie Xu57dd9612017-08-17 17:50:56 -0700421// Construct a CHUNK_RAW patch from the target data directly.
422PatchChunk::PatchChunk(const ImageChunk& tgt)
423 : type_(CHUNK_RAW),
424 source_start_(0),
425 source_len_(0),
426 source_uncompressed_len_(0),
427 target_start_(tgt.GetStartOffset()),
428 target_len_(tgt.GetRawDataLength()),
429 target_uncompressed_len_(tgt.DataLengthForPatch()),
430 target_compress_level_(tgt.GetCompressLevel()),
431 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700432
433// Return true if raw data is smaller than the patch size.
434bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
435 size_t target_len = tgt.GetRawDataLength();
436 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
437}
438
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700439void PatchChunk::UpdateSourceOffset(const SortedRangeSet& src_range) {
440 if (type_ == CHUNK_DEFLATE) {
441 source_start_ = src_range.GetOffsetInRangeSet(source_start_);
442 }
443}
444
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700445// Header size:
446// header_type 4 bytes
447// CHUNK_NORMAL 8*3 = 24 bytes
448// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
449// CHUNK_RAW 4 bytes + patch_size
450size_t PatchChunk::GetHeaderSize() const {
451 switch (type_) {
452 case CHUNK_NORMAL:
453 return 4 + 8 * 3;
454 case CHUNK_DEFLATE:
455 return 4 + 8 * 5 + 4 * 5;
456 case CHUNK_RAW:
457 return 4 + 4 + data_.size();
458 default:
459 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
460 return 0;
461 }
462}
463
464// Return the offset of the next patch into the patch data.
465size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
466 Write4(fd, type_);
467 switch (type_) {
468 case CHUNK_NORMAL:
469 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
470 Write8(fd, static_cast<int64_t>(source_start_));
471 Write8(fd, static_cast<int64_t>(source_len_));
472 Write8(fd, static_cast<int64_t>(offset));
473 return offset + data_.size();
474 case CHUNK_DEFLATE:
475 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
476 Write8(fd, static_cast<int64_t>(source_start_));
477 Write8(fd, static_cast<int64_t>(source_len_));
478 Write8(fd, static_cast<int64_t>(offset));
479 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
480 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
481 Write4(fd, target_compress_level_);
482 Write4(fd, ImageChunk::METHOD);
483 Write4(fd, ImageChunk::WINDOWBITS);
484 Write4(fd, ImageChunk::MEMLEVEL);
485 Write4(fd, ImageChunk::STRATEGY);
486 return offset + data_.size();
487 case CHUNK_RAW:
488 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
489 Write4(fd, static_cast<int32_t>(data_.size()));
490 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
491 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
492 }
493 return offset;
494 default:
495 CHECK(false) << "unexpected chunk type: " << type_;
496 return offset;
497 }
498}
499
500// Write the contents of |patch_chunks| to |patch_fd|.
501bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
502 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
503 // the offset of each bsdiff patch within the file.
504 size_t total_header_size = 12;
505 for (const auto& patch : patch_chunks) {
506 total_header_size += patch.GetHeaderSize();
507 }
508
509 size_t offset = total_header_size;
510
511 // Write out the headers.
512 if (!android::base::WriteStringToFd("IMGDIFF2", patch_fd)) {
513 printf("failed to write \"IMGDIFF2\": %s\n", strerror(errno));
514 return false;
515 }
516
517 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
518 for (size_t i = 0; i < patch_chunks.size(); ++i) {
519 printf("chunk %zu: ", i);
520 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
521 }
522
523 // Append each chunk's bsdiff patch, in order.
524 for (const auto& patch : patch_chunks) {
525 if (patch.type_ == CHUNK_RAW) {
526 continue;
527 }
528 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
529 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
530 return false;
531 }
532 }
533
534 return true;
535}
536
Tianjie Xu57dd9612017-08-17 17:50:56 -0700537ImageChunk& Image::operator[](size_t i) {
538 CHECK_LT(i, chunks_.size());
539 return chunks_[i];
540}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700541
Tianjie Xu57dd9612017-08-17 17:50:56 -0700542const ImageChunk& Image::operator[](size_t i) const {
543 CHECK_LT(i, chunks_.size());
544 return chunks_[i];
545}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700546
547void Image::MergeAdjacentNormalChunks() {
548 size_t merged_last = 0, cur = 0;
549 while (cur < chunks_.size()) {
550 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
551 // length of the current normal chunk.
552 size_t to_check = cur + 1;
553 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
554 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
555 to_check++;
556 }
557
558 if (merged_last != cur) {
559 chunks_[merged_last] = std::move(chunks_[cur]);
560 }
561 merged_last++;
562 cur = to_check;
563 }
564 if (merged_last < chunks_.size()) {
565 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
566 }
567}
568
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700569void Image::DumpChunks() const {
570 std::string type = is_source_ ? "source" : "target";
571 printf("Dumping chunks for %s\n", type.c_str());
572 for (size_t i = 0; i < chunks_.size(); ++i) {
573 printf("chunk %zu: ", i);
574 chunks_[i].Dump();
575 }
576}
577
578bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
579 CHECK(file_content != nullptr);
580
581 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
582 if (fd == -1) {
583 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
584 return false;
585 }
586 struct stat st;
587 if (fstat(fd, &st) != 0) {
588 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
589 return false;
590 }
591
592 size_t sz = static_cast<size_t>(st.st_size);
593 file_content->resize(sz);
594 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
595 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
596 return false;
597 }
598 fd.reset();
599
600 return true;
601}
602
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700603bool ZipModeImage::Initialize(const std::string& filename) {
604 if (!ReadFile(filename, &file_content_)) {
605 return false;
606 }
607
608 // Omit the trailing zeros before we pass the file to ziparchive handler.
609 size_t zipfile_size;
610 if (!GetZipFileSize(&zipfile_size)) {
611 printf("failed to parse the actual size of %s\n", filename.c_str());
612 return false;
613 }
614 ZipArchiveHandle handle;
615 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
616 filename.c_str(), &handle);
617 if (err != 0) {
618 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
619 CloseArchive(handle);
620 return false;
621 }
622
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700623 if (!InitializeChunks(filename, handle)) {
624 CloseArchive(handle);
625 return false;
626 }
627
628 CloseArchive(handle);
629 return true;
630}
631
632// Iterate the zip entries and compose the image chunks accordingly.
633bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
634 void* cookie;
635 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
636 if (ret != 0) {
637 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
638 return false;
639 }
640
641 // Create a list of deflated zip entries, sorted by offset.
642 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
643 ZipString name;
644 ZipEntry entry;
645 while ((ret = Next(cookie, &entry, &name)) == 0) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700646 if (entry.method == kCompressDeflated || limit_ > 0) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700647 std::string entry_name(name.name, name.name + name.name_length);
648 temp_entries.emplace_back(entry_name, entry);
649 }
650 }
651
652 if (ret != -1) {
653 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
654 return false;
655 }
656 std::sort(temp_entries.begin(), temp_entries.end(),
657 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
658
659 EndIteration(cookie);
660
661 // For source chunks, we don't need to compose chunks for the metadata.
662 if (is_source_) {
663 for (auto& entry : temp_entries) {
664 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
665 printf("Failed to add %s to source chunks\n", entry.first.c_str());
666 return false;
667 }
668 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700669
670 // Add the end of zip file (mainly central directory) as a normal chunk.
671 size_t entries_end = 0;
672 if (!temp_entries.empty()) {
673 entries_end = static_cast<size_t>(temp_entries.back().second.offset +
674 temp_entries.back().second.compressed_length);
675 }
676 CHECK_LT(entries_end, file_content_.size());
677 chunks_.emplace_back(CHUNK_NORMAL, entries_end, &file_content_,
678 file_content_.size() - entries_end);
679
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700680 return true;
681 }
682
683 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
684 // deflate entries as CHUNK_NORMAL.
685 size_t pos = 0;
686 size_t nextentry = 0;
687 while (pos < file_content_.size()) {
688 if (nextentry < temp_entries.size() &&
689 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
690 // Add the next zip entry.
691 std::string entry_name = temp_entries[nextentry].first;
692 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
693 printf("Failed to add %s to target chunks\n", entry_name.c_str());
694 return false;
695 }
696
697 pos += temp_entries[nextentry].second.compressed_length;
698 ++nextentry;
699 continue;
700 }
701
702 // Use a normal chunk to take all the data up to the start of the next entry.
703 size_t raw_data_len;
704 if (nextentry < temp_entries.size()) {
705 raw_data_len = temp_entries[nextentry].second.offset - pos;
706 } else {
707 raw_data_len = file_content_.size() - pos;
708 }
709 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
710
711 pos += raw_data_len;
712 }
713
714 return true;
715}
716
717bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
718 ZipEntry* entry) {
719 size_t compressed_len = entry->compressed_length;
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700720 if (compressed_len == 0) return true;
721
722 // Split the entry into several normal chunks if it's too large.
723 if (limit_ > 0 && compressed_len > limit_) {
724 int count = 0;
725 while (compressed_len > 0) {
726 size_t length = std::min(limit_, compressed_len);
727 std::string name = entry_name + "-" + std::to_string(count);
728 chunks_.emplace_back(CHUNK_NORMAL, entry->offset + limit_ * count, &file_content_, length,
729 name);
730
731 count++;
732 compressed_len -= length;
733 }
734 } else if (entry->method == kCompressDeflated) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700735 size_t uncompressed_len = entry->uncompressed_length;
736 std::vector<uint8_t> uncompressed_data(uncompressed_len);
737 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
738 if (ret != 0) {
739 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
740 ErrorCodeString(ret));
741 return false;
742 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700743 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700744 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700745 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700746 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700747 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700748 }
749
750 return true;
751}
752
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800753// EOCD record
754// offset 0: signature 0x06054b50, 4 bytes
755// offset 4: number of this disk, 2 bytes
756// ...
757// offset 20: comment length, 2 bytes
758// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700759bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
760 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800761 printf("file is too small to be a zip file\n");
762 return false;
763 }
764
765 // Look for End of central directory record of the zip file, and calculate the actual
766 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700767 for (int i = file_content_.size() - 22; i >= 0; i--) {
768 if (file_content_[i] == 0x50) {
769 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800770 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700771 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800772
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700773 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800774 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700775 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800776 *input_file_size = file_size;
777 return true;
778 }
779 }
780 }
781
782 // EOCD not found, this file is likely not a valid zip file.
783 return false;
784}
785
Tianjie Xu57dd9612017-08-17 17:50:56 -0700786ImageChunk ZipModeImage::PseudoSource() const {
787 CHECK(is_source_);
788 return ImageChunk(CHUNK_NORMAL, 0, &file_content_, file_content_.size());
789}
790
791const ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) const {
792 if (name.empty()) {
793 return nullptr;
794 }
795 for (auto& chunk : chunks_) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700796 if (chunk.GetType() != CHUNK_DEFLATE && !find_normal) {
797 continue;
798 }
799
800 if (chunk.GetEntryName() == name) {
Tianjie Xu57dd9612017-08-17 17:50:56 -0700801 return &chunk;
802 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700803
804 // Edge case when target chunk is split due to size limit but source chunk isn't.
805 if (name == (chunk.GetEntryName() + "-0") || chunk.GetEntryName() == (name + "-0")) {
806 return &chunk;
807 }
808
809 // TODO handle the .so files with incremental version number.
810 // (e.g. lib/arm64-v8a/libcronet.59.0.3050.4.so)
Tianjie Xu57dd9612017-08-17 17:50:56 -0700811 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700812
Tianjie Xu57dd9612017-08-17 17:50:56 -0700813 return nullptr;
814}
815
816ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) {
817 return const_cast<ImageChunk*>(
818 static_cast<const ZipModeImage*>(this)->FindChunkByName(name, find_normal));
819}
820
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700821bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
822 for (auto& tgt_chunk : *tgt_image) {
823 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800824 continue;
825 }
826
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700827 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
828 if (src_chunk == nullptr) {
829 tgt_chunk.ChangeDeflateChunkToNormal();
830 } else if (tgt_chunk == *src_chunk) {
831 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
832 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
833 // patch to the compressed data, rather than uncompressing and recompressing to apply the
834 // trivial patch to the uncompressed data.
835 tgt_chunk.ChangeDeflateChunkToNormal();
836 src_chunk->ChangeDeflateChunkToNormal();
837 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
838 // We cannot recompress the data and get exactly the same bits as are in the input target
839 // image. Treat the chunk as a normal non-deflated chunk.
840 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
841 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800842
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700843 tgt_chunk.ChangeDeflateChunkToNormal();
844 src_chunk->ChangeDeflateChunkToNormal();
845 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800846 }
847
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700848 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
849 // filename, and normal chunks are patched using the entire source file as the source.
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700850 if (tgt_image->limit_ == 0) {
851 tgt_image->MergeAdjacentNormalChunks();
852 tgt_image->DumpChunks();
853 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800854
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700855 return true;
856}
857
Tianjie Xu2903cdd2017-08-18 18:15:47 -0700858// For each target chunk, look for the corresponding source chunk by the zip_entry name. If
859// found, add the range of this chunk in the original source file to the block aligned source
860// ranges. Construct the split src & tgt image once the size of source range reaches limit.
861bool ZipModeImage::SplitZipModeImageWithLimit(const ZipModeImage& tgt_image,
862 const ZipModeImage& src_image,
863 std::vector<ZipModeImage>* split_tgt_images,
864 std::vector<ZipModeImage>* split_src_images,
865 std::vector<SortedRangeSet>* split_src_ranges) {
866 CHECK_EQ(tgt_image.limit_, src_image.limit_);
867 size_t limit = tgt_image.limit_;
868
869 src_image.DumpChunks();
870 printf("Splitting %zu tgt chunks...\n", tgt_image.NumOfChunks());
871
872 SortedRangeSet used_src_ranges; // ranges used for previous split source images.
873
874 // Reserve the central directory in advance for the last split image.
875 const auto& central_directory = src_image.cend() - 1;
876 CHECK_EQ(CHUNK_NORMAL, central_directory->GetType());
877 used_src_ranges.Insert(central_directory->GetStartOffset(),
878 central_directory->DataLengthForPatch());
879
880 SortedRangeSet src_ranges;
881 std::vector<ImageChunk> split_src_chunks;
882 std::vector<ImageChunk> split_tgt_chunks;
883 for (auto tgt = tgt_image.cbegin(); tgt != tgt_image.cend(); tgt++) {
884 const ImageChunk* src = src_image.FindChunkByName(tgt->GetEntryName(), true);
885 if (src == nullptr) {
886 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
887 tgt->GetRawDataLength());
888 continue;
889 }
890
891 size_t src_offset = src->GetStartOffset();
892 size_t src_length = src->GetRawDataLength();
893
894 CHECK(src_length > 0);
895 CHECK_LE(src_length, limit);
896
897 // Make sure this source range hasn't been used before so that the src_range pieces don't
898 // overlap with each other.
899 if (!RemoveUsedBlocks(&src_offset, &src_length, used_src_ranges)) {
900 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
901 tgt->GetRawDataLength());
902 } else if (src_ranges.blocks() * BLOCK_SIZE + src_length <= limit) {
903 src_ranges.Insert(src_offset, src_length);
904
905 // Add the deflate source chunk if it hasn't been aligned.
906 if (src->GetType() == CHUNK_DEFLATE && src_length == src->GetRawDataLength()) {
907 split_src_chunks.push_back(*src);
908 split_tgt_chunks.push_back(*tgt);
909 } else {
910 // TODO split smarter to avoid alignment of large deflate chunks
911 split_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt->GetStartOffset(), &tgt_image.file_content_,
912 tgt->GetRawDataLength());
913 }
914 } else {
915 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
916 split_src_chunks, split_tgt_images,
917 split_src_images);
918
919 split_tgt_chunks.clear();
920 split_src_chunks.clear();
921 used_src_ranges.Insert(src_ranges);
922 split_src_ranges->push_back(std::move(src_ranges));
923 src_ranges.Clear();
924
925 // We don't have enough space for the current chunk; start a new split image and handle
926 // this chunk there.
927 tgt--;
928 }
929 }
930
931 // TODO Trim it in case the CD exceeds limit too much.
932 src_ranges.Insert(central_directory->GetStartOffset(), central_directory->DataLengthForPatch());
933 ZipModeImage::AddSplitImageFromChunkList(tgt_image, src_image, src_ranges, split_tgt_chunks,
934 split_src_chunks, split_tgt_images, split_src_images);
935 split_src_ranges->push_back(std::move(src_ranges));
936
937 ValidateSplitImages(*split_tgt_images, *split_src_images, *split_src_ranges,
938 tgt_image.file_content_.size());
939
940 return true;
941}
942
943void ZipModeImage::AddSplitImageFromChunkList(const ZipModeImage& tgt_image,
944 const ZipModeImage& src_image,
945 const SortedRangeSet& split_src_ranges,
946 const std::vector<ImageChunk>& split_tgt_chunks,
947 const std::vector<ImageChunk>& split_src_chunks,
948 std::vector<ZipModeImage>* split_tgt_images,
949 std::vector<ZipModeImage>* split_src_images) {
950 CHECK(!split_tgt_chunks.empty());
951 // Target chunks should occupy at least one block.
952 // TODO put a warning and change the type to raw if it happens in extremely rare cases.
953 size_t tgt_size = split_tgt_chunks.back().GetStartOffset() +
954 split_tgt_chunks.back().DataLengthForPatch() -
955 split_tgt_chunks.front().GetStartOffset();
956 CHECK_GE(tgt_size, BLOCK_SIZE);
957
958 std::vector<ImageChunk> aligned_tgt_chunks;
959
960 // Align the target chunks in the beginning with BLOCK_SIZE.
961 size_t i = 0;
962 while (i < split_tgt_chunks.size()) {
963 size_t tgt_start = split_tgt_chunks[i].GetStartOffset();
964 size_t tgt_length = split_tgt_chunks[i].GetRawDataLength();
965
966 // Current ImageChunk is long enough to align.
967 if (AlignHead(&tgt_start, &tgt_length)) {
968 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, tgt_start, &tgt_image.file_content_,
969 tgt_length);
970 break;
971 }
972
973 i++;
974 }
975 CHECK_LT(i, split_tgt_chunks.size());
976 aligned_tgt_chunks.insert(aligned_tgt_chunks.end(), split_tgt_chunks.begin() + i + 1,
977 split_tgt_chunks.end());
978 CHECK(!aligned_tgt_chunks.empty());
979
980 // Add a normal chunk to align the contents in the end.
981 size_t end_offset =
982 aligned_tgt_chunks.back().GetStartOffset() + aligned_tgt_chunks.back().GetRawDataLength();
983 if (end_offset % BLOCK_SIZE != 0 && end_offset < tgt_image.file_content_.size()) {
984 aligned_tgt_chunks.emplace_back(CHUNK_NORMAL, end_offset, &tgt_image.file_content_,
985 BLOCK_SIZE - (end_offset % BLOCK_SIZE));
986 }
987
988 ZipModeImage split_tgt_image(false);
989 split_tgt_image.Initialize(std::move(aligned_tgt_chunks), {});
990 split_tgt_image.MergeAdjacentNormalChunks();
991
992 // Construct the dummy source file based on the src_ranges.
993 std::vector<uint8_t> src_content;
994 for (const auto& r : split_src_ranges) {
995 size_t end = std::min(src_image.file_content_.size(), r.second * BLOCK_SIZE);
996 src_content.insert(src_content.end(), src_image.file_content_.begin() + r.first * BLOCK_SIZE,
997 src_image.file_content_.begin() + end);
998 }
999
1000 // We should not have an empty src in our design; otherwise we will encounter an error in
1001 // bsdiff since src_content.data() == nullptr.
1002 CHECK(!src_content.empty());
1003
1004 ZipModeImage split_src_image(true);
1005 split_src_image.Initialize(split_src_chunks, std::move(src_content));
1006
1007 split_tgt_images->push_back(std::move(split_tgt_image));
1008 split_src_images->push_back(std::move(split_src_image));
1009}
1010
1011void ZipModeImage::ValidateSplitImages(const std::vector<ZipModeImage>& split_tgt_images,
1012 const std::vector<ZipModeImage>& split_src_images,
1013 std::vector<SortedRangeSet>& split_src_ranges,
1014 size_t total_tgt_size) {
1015 CHECK_EQ(split_tgt_images.size(), split_src_images.size());
1016
1017 printf("Validating %zu images\n", split_tgt_images.size());
1018
1019 // Verify that the target image pieces is continuous and can add up to the total size.
1020 size_t last_offset = 0;
1021 for (const auto& tgt_image : split_tgt_images) {
1022 CHECK(!tgt_image.chunks_.empty());
1023
1024 CHECK_EQ(last_offset, tgt_image.chunks_.front().GetStartOffset());
1025 CHECK(last_offset % BLOCK_SIZE == 0);
1026
1027 // Check the target chunks within the split image are continuous.
1028 for (const auto& chunk : tgt_image.chunks_) {
1029 CHECK_EQ(last_offset, chunk.GetStartOffset());
1030 last_offset += chunk.GetRawDataLength();
1031 }
1032 }
1033 CHECK_EQ(total_tgt_size, last_offset);
1034
1035 // Verify that the source ranges are mutually exclusive.
1036 CHECK_EQ(split_src_images.size(), split_src_ranges.size());
1037 SortedRangeSet used_src_ranges;
1038 for (size_t i = 0; i < split_src_ranges.size(); i++) {
1039 CHECK(!used_src_ranges.Overlaps(split_src_ranges[i]))
1040 << "src range " << split_src_ranges[i].ToString() << " overlaps "
1041 << used_src_ranges.ToString();
1042 used_src_ranges.Insert(split_src_ranges[i]);
1043 }
1044}
1045
1046bool ZipModeImage::GeneratePatchesInternal(const ZipModeImage& tgt_image,
1047 const ZipModeImage& src_image,
1048 std::vector<PatchChunk>* patch_chunks) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001049 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001050 patch_chunks->clear();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001051
1052 saidx_t* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001053 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1054 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001055
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001056 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001057 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001058 continue;
1059 }
1060
1061 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
1062 ? nullptr
1063 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
1064
1065 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001066 saidx_t** bsdiff_cache_ptr = (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
1067
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001068 std::vector<uint8_t> patch_data;
1069 if (!ImageChunk::MakePatch(tgt_chunk, src_ref, &patch_data, bsdiff_cache_ptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001070 printf("Failed to generate patch, name: %s\n", tgt_chunk.GetEntryName().c_str());
1071 return false;
1072 }
1073
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001074 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001075 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001076
1077 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001078 patch_chunks->emplace_back(tgt_chunk);
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001079 } else {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001080 patch_chunks->emplace_back(tgt_chunk, src_ref, std::move(patch_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001081 }
Tianjie Xu12b90552017-03-07 14:44:14 -08001082 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001083 free(bsdiff_cache);
1084
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001085 CHECK_EQ(patch_chunks->size(), tgt_image.NumOfChunks());
1086 return true;
1087}
1088
1089bool ZipModeImage::GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
1090 const std::string& patch_name) {
1091 std::vector<PatchChunk> patch_chunks;
1092
1093 ZipModeImage::GeneratePatchesInternal(tgt_image, src_image, &patch_chunks);
1094
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001095 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1096
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001097 android::base::unique_fd patch_fd(
1098 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1099 if (patch_fd == -1) {
1100 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001101 return false;
1102 }
1103
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001104 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001105}
1106
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001107bool ZipModeImage::GeneratePatches(const std::vector<ZipModeImage>& split_tgt_images,
1108 const std::vector<ZipModeImage>& split_src_images,
1109 const std::vector<SortedRangeSet>& split_src_ranges,
1110 const std::string& patch_name, const std::string& debug_dir) {
1111 printf("Construct patches for %zu split images...\n", split_tgt_images.size());
1112
1113 android::base::unique_fd patch_fd(
1114 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1115 if (patch_fd == -1) {
1116 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1117 return false;
1118 }
1119
1120 for (size_t i = 0; i < split_tgt_images.size(); i++) {
1121 std::vector<PatchChunk> patch_chunks;
1122 if (!ZipModeImage::GeneratePatchesInternal(split_tgt_images[i], split_src_images[i],
1123 &patch_chunks)) {
1124 printf("failed to generate split patch\n");
1125 return false;
1126 }
1127
1128 for (auto& p : patch_chunks) {
1129 p.UpdateSourceOffset(split_src_ranges[i]);
1130 }
1131
1132 if (!PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd)) {
1133 return false;
1134 }
1135
1136 // Write the split source & patch into the debug directory.
1137 if (!debug_dir.empty()) {
1138 std::string src_name = android::base::StringPrintf("%s/src-%zu", debug_dir.c_str(), i);
1139 android::base::unique_fd fd(
1140 open(src_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1141
1142 if (fd == -1) {
1143 printf("Failed to open %s\n", src_name.c_str());
1144 return false;
1145 }
1146 if (!android::base::WriteFully(fd, split_src_images[i].PseudoSource().DataForPatch(),
1147 split_src_images[i].PseudoSource().DataLengthForPatch())) {
1148 printf("Failed to write split source data into %s\n", src_name.c_str());
1149 return false;
1150 }
1151
1152 std::string patch_name = android::base::StringPrintf("%s/patch-%zu", debug_dir.c_str(), i);
1153 fd.reset(open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1154
1155 if (fd == -1) {
1156 printf("Failed to open %s\n", patch_name.c_str());
1157 return false;
1158 }
1159 if (!PatchChunk::WritePatchDataToFd(patch_chunks, fd)) {
1160 return false;
1161 }
1162 }
1163 }
1164 return true;
1165}
1166
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001167bool ImageModeImage::Initialize(const std::string& filename) {
1168 if (!ReadFile(filename, &file_content_)) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001169 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001170 }
Doug Zongker512536a2010-02-17 16:11:44 -08001171
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001172 size_t sz = file_content_.size();
Doug Zongker512536a2010-02-17 16:11:44 -08001173 size_t pos = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -07001174 while (pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001175 // 0x00 no header flags, 0x08 deflate compression, 0x1f8b gzip magic number
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001176 if (sz - pos >= 4 && get_unaligned<uint32_t>(file_content_.data() + pos) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001177 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +02001178 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001179
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001180 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
1181 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001182 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, sz - pos);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001183 break;
1184 }
Doug Zongker512536a2010-02-17 16:11:44 -08001185
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001186 // We need three chunks for the deflated image in total, one normal chunk for the header,
1187 // one deflated chunk for the body, and another normal chunk for the footer.
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001188 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_HEADER_LEN);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001189 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001190
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001191 // We must decompress this chunk in order to discover where it ends, and so we can update
1192 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -08001193
1194 z_stream strm;
1195 strm.zalloc = Z_NULL;
1196 strm.zfree = Z_NULL;
1197 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -07001198 strm.avail_in = sz - pos;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001199 strm.next_in = file_content_.data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001200
1201 // -15 means we are decoding a 'raw' deflate stream; zlib will
1202 // not expect zlib headers.
1203 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001204 if (ret < 0) {
1205 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001206 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001207 }
Doug Zongker512536a2010-02-17 16:11:44 -08001208
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001209 size_t allocated = BUFFER_SIZE;
1210 std::vector<uint8_t> uncompressed_data(allocated);
1211 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001212 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001213 strm.avail_out = allocated - uncompressed_len;
1214 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001215 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +02001216 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001217 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -08001218 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001219 break;
Johan Redestigc68bd342015-04-14 21:20:06 +02001220 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001221 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -08001222 if (strm.avail_out == 0) {
1223 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001224 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -08001225 }
1226 } while (ret != Z_STREAM_END);
1227
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001228 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001229 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001230
1231 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001232 continue;
1233 }
1234
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001235 // The footer contains the size of the uncompressed data. Double-check to make sure that it
1236 // matches the size of the data we got when we actually did the decompression.
1237 size_t footer_index = pos + raw_data_len + GZIP_FOOTER_LEN - 4;
1238 if (sz - footer_index < 4) {
1239 printf("Warning: invalid footer position; treating as a nomal chunk\n");
1240 continue;
1241 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001242 size_t footer_size = get_unaligned<uint32_t>(file_content_.data() + footer_index);
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001243 if (footer_size != uncompressed_len) {
1244 printf("Warning: footer size %zu != decompressed size %zu; treating as a nomal chunk\n",
1245 footer_size, uncompressed_len);
1246 continue;
1247 }
1248
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001249 ImageChunk body(CHUNK_DEFLATE, pos, &file_content_, raw_data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001250 uncompressed_data.resize(uncompressed_len);
1251 body.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001252 chunks_.push_back(std::move(body));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001253
1254 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001255
1256 // create a normal chunk for the footer
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001257 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -08001258
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001259 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001260 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001261 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
1262 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -08001263
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001264 // Scan forward until we find a gzip header.
1265 size_t data_len = 0;
1266 while (data_len + pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001267 if (data_len + pos + 4 <= sz &&
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001268 get_unaligned<uint32_t>(file_content_.data() + pos + data_len) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001269 break;
1270 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001271 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -08001272 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001273 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001274
1275 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001276 }
1277 }
1278
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001279 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001280}
1281
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001282bool ImageModeImage::SetBonusData(const std::vector<uint8_t>& bonus_data) {
1283 CHECK(is_source_);
1284 if (chunks_.size() < 2 || !chunks_[1].SetBonusData(bonus_data)) {
1285 printf("Failed to set bonus data\n");
1286 DumpChunks();
1287 return false;
1288 }
1289
1290 printf(" using %zu bytes of bonus data\n", bonus_data.size());
1291 return true;
1292}
1293
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001294// In Image Mode, verify that the source and target images have the same chunk structure (ie, the
1295// same sequence of deflate and normal chunks).
1296bool ImageModeImage::CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image) {
1297 // In image mode, merge the gzip header and footer in with any adjacent normal chunks.
1298 tgt_image->MergeAdjacentNormalChunks();
1299 src_image->MergeAdjacentNormalChunks();
Doug Zongker512536a2010-02-17 16:11:44 -08001300
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001301 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1302 printf("source and target don't have same number of chunks!\n");
1303 tgt_image->DumpChunks();
1304 src_image->DumpChunks();
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001305 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +02001306 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001307 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001308 if ((*tgt_image)[i].GetType() != (*src_image)[i].GetType()) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001309 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
1310 tgt_image->DumpChunks();
1311 src_image->DumpChunks();
1312 return false;
1313 }
Doug Zongker512536a2010-02-17 16:11:44 -08001314 }
1315
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001316 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001317 auto& tgt_chunk = (*tgt_image)[i];
1318 auto& src_chunk = (*src_image)[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001319 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
1320 continue;
1321 }
1322
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001323 // If two deflate chunks are identical treat them as normal chunks.
1324 if (tgt_chunk == src_chunk) {
1325 tgt_chunk.ChangeDeflateChunkToNormal();
1326 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001327 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
1328 // We cannot recompress the data and get exactly the same bits as are in the input target
1329 // image, fall back to normal
1330 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
1331 tgt_chunk.GetEntryName().c_str());
1332 tgt_chunk.ChangeDeflateChunkToNormal();
1333 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001334 }
Doug Zongker512536a2010-02-17 16:11:44 -08001335 }
1336
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001337 // For images, we need to maintain the parallel structure of the chunk lists, so do the merging
1338 // in both the source and target lists.
1339 tgt_image->MergeAdjacentNormalChunks();
1340 src_image->MergeAdjacentNormalChunks();
1341 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1342 // This shouldn't happen.
1343 printf("merging normal chunks went awry\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001344 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001345 }
Doug Zongker512536a2010-02-17 16:11:44 -08001346
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001347 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001348}
1349
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001350// In image mode, generate patches against the given source chunks and bonus_data; write the
1351// result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001352bool ImageModeImage::GeneratePatches(const ImageModeImage& tgt_image,
1353 const ImageModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001354 const std::string& patch_name) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001355 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
1356 std::vector<PatchChunk> patch_chunks;
1357 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001358
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001359 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1360 const auto& tgt_chunk = tgt_image[i];
1361 const auto& src_chunk = src_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001362
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001363 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
1364 patch_chunks.emplace_back(tgt_chunk);
1365 continue;
Doug Zongker512536a2010-02-17 16:11:44 -08001366 }
1367
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001368 std::vector<uint8_t> patch_data;
1369 if (!ImageChunk::MakePatch(tgt_chunk, src_chunk, &patch_data, nullptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001370 printf("Failed to generate patch for target chunk %zu: ", i);
1371 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001372 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001373 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001374 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001375
1376 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
1377 patch_chunks.emplace_back(tgt_chunk);
1378 } else {
1379 patch_chunks.emplace_back(tgt_chunk, src_chunk, std::move(patch_data));
1380 }
Doug Zongker512536a2010-02-17 16:11:44 -08001381 }
Doug Zongker512536a2010-02-17 16:11:44 -08001382
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001383 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1384
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001385 android::base::unique_fd patch_fd(
1386 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1387 if (patch_fd == -1) {
1388 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1389 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001390 }
Doug Zongker512536a2010-02-17 16:11:44 -08001391
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001392 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Doug Zongker512536a2010-02-17 16:11:44 -08001393}
1394
Tao Bao97555da2016-12-15 10:15:06 -08001395int imgdiff(int argc, const char** argv) {
1396 bool zip_mode = false;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001397 std::vector<uint8_t> bonus_data;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001398 size_t blocks_limit = 0;
1399 std::string debug_dir;
Tianjie Xu12b90552017-03-07 14:44:14 -08001400
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001401 int opt;
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001402 int option_index;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001403 optind = 1; // Reset the getopt state so that we can call it multiple times for test.
Doug Zongkera3ccba62012-08-20 15:28:02 -07001404
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001405 while ((opt = getopt_long(argc, const_cast<char**>(argv), "zb:", OPTIONS, &option_index)) != -1) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001406 switch (opt) {
1407 case 'z':
1408 zip_mode = true;
1409 break;
1410 case 'b': {
1411 android::base::unique_fd fd(open(optarg, O_RDONLY));
1412 if (fd == -1) {
1413 printf("failed to open bonus file %s: %s\n", optarg, strerror(errno));
1414 return 1;
1415 }
1416 struct stat st;
1417 if (fstat(fd, &st) != 0) {
1418 printf("failed to stat bonus file %s: %s\n", optarg, strerror(errno));
1419 return 1;
1420 }
1421
1422 size_t bonus_size = st.st_size;
1423 bonus_data.resize(bonus_size);
1424 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
1425 printf("failed to read bonus file %s: %s\n", optarg, strerror(errno));
1426 return 1;
1427 }
1428 break;
1429 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001430 case 0: {
1431 std::string name = OPTIONS[option_index].name;
1432 if (name == "block-limit" && !android::base::ParseUint(optarg, &blocks_limit)) {
1433 printf("failed to parse size blocks_limit: %s\n", optarg);
1434 return 1;
1435 } else if (name == "debug-dir") {
1436 debug_dir = optarg;
1437 }
1438 break;
1439 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001440 default:
1441 printf("unexpected opt: %s\n", optarg);
1442 return 2;
1443 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001444 }
1445
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001446 if (argc - optind != 3) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001447 printf("usage: %s [options] <src-img> <tgt-img> <patch-file>\n", argv[0]);
1448 printf(
1449 " -z <zip-mode>, Generate patches in zip mode, src and tgt should be zip files.\n"
1450 " -b <bonus-file>, Bonus file in addition to src, image mode only.\n"
1451 " --block-limit, For large zips, split the src and tgt based on the block limit;\n"
1452 " and generate patches between each pair of pieces. Concatenate these\n"
1453 " patches together and output them into <patch-file>.\n"
1454 " --debug_dir, Debug directory to put the split srcs and patches, zip mode only.\n");
Doug Zongkera3ccba62012-08-20 15:28:02 -07001455 return 2;
1456 }
Doug Zongker512536a2010-02-17 16:11:44 -08001457
Doug Zongker512536a2010-02-17 16:11:44 -08001458 if (zip_mode) {
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001459 ZipModeImage src_image(true, blocks_limit * BLOCK_SIZE);
1460 ZipModeImage tgt_image(false, blocks_limit * BLOCK_SIZE);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001461
1462 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001463 return 1;
1464 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001465 if (!tgt_image.Initialize(argv[optind + 1])) {
1466 return 1;
1467 }
1468
1469 if (!ZipModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
1470 return 1;
1471 }
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001472
1473 // TODO save and output the split information so that caller can create split transfer lists
1474 // accordingly.
1475
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001476 // Compute bsdiff patches for each chunk's data (the uncompressed data, in the case of
1477 // deflate chunks).
Tianjie Xu2903cdd2017-08-18 18:15:47 -07001478 if (blocks_limit > 0) {
1479 std::vector<ZipModeImage> split_tgt_images;
1480 std::vector<ZipModeImage> split_src_images;
1481 std::vector<SortedRangeSet> split_src_ranges;
1482 ZipModeImage::SplitZipModeImageWithLimit(tgt_image, src_image, &split_tgt_images,
1483 &split_src_images, &split_src_ranges);
1484
1485 if (!ZipModeImage::GeneratePatches(split_tgt_images, split_src_images, split_src_ranges,
1486 argv[optind + 2], debug_dir)) {
1487 return 1;
1488 }
1489
1490 } else if (!ZipModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001491 return 1;
1492 }
1493 } else {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001494 ImageModeImage src_image(true);
1495 ImageModeImage tgt_image(false);
1496
1497 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001498 return 1;
1499 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001500 if (!tgt_image.Initialize(argv[optind + 1])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001501 return 1;
1502 }
1503
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001504 if (!ImageModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
Doug Zongker512536a2010-02-17 16:11:44 -08001505 return 1;
1506 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001507
1508 if (!bonus_data.empty() && !src_image.SetBonusData(bonus_data)) {
1509 return 1;
1510 }
1511
1512 if (!ImageModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001513 return 1;
1514 }
1515 }
1516
Doug Zongker512536a2010-02-17 16:11:44 -08001517 return 0;
1518}