blob: 59b600713111cee1c7e539f496fb338bf773e6ef [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>
Doug Zongker512536a2010-02-17 16:11:44 -0800128#include <stdio.h>
129#include <stdlib.h>
130#include <string.h>
131#include <sys/stat.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800132#include <sys/types.h>
Tao Bao97555da2016-12-15 10:15:06 -0800133#include <unistd.h>
Doug Zongker512536a2010-02-17 16:11:44 -0800134
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800135#include <algorithm>
136#include <string>
137#include <vector>
138
Tao Baod37ce8f2016-12-17 17:10:04 -0800139#include <android-base/file.h>
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800140#include <android-base/logging.h>
141#include <android-base/memory.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800142#include <android-base/unique_fd.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700143#include <bsdiff.h>
Tianjie Xu57dd9612017-08-17 17:50:56 -0700144#include <ziparchive/zip_archive.h>
Tao Bao97555da2016-12-15 10:15:06 -0800145#include <zlib.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700146
Tianjie Xu57dd9612017-08-17 17:50:56 -0700147#include "applypatch/imgdiff_image.h"
148
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800149using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800150
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800151static constexpr auto BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800152
Tianjie Xu12b90552017-03-07 14:44:14 -0800153// If we use this function to write the offset and length (type size_t), their values should not
154// exceed 2^63; because the signed bit will be casted away.
155static inline bool Write8(int fd, int64_t value) {
156 return android::base::WriteFully(fd, &value, sizeof(int64_t));
157}
158
159// Similarly, the value should not exceed 2^31 if we are casting from size_t (e.g. target chunk
160// size).
161static inline bool Write4(int fd, int32_t value) {
162 return android::base::WriteFully(fd, &value, sizeof(int32_t));
163}
164
Tianjie Xu57dd9612017-08-17 17:50:56 -0700165ImageChunk::ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content,
166 size_t raw_data_len, std::string entry_name)
167 : type_(type),
168 start_(start),
169 input_file_ptr_(file_content),
170 raw_data_len_(raw_data_len),
171 compress_level_(6),
172 entry_name_(std::move(entry_name)) {
173 CHECK(file_content != nullptr) << "input file container can't be nullptr";
174}
Doug Zongker512536a2010-02-17 16:11:44 -0800175
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800176const uint8_t* ImageChunk::GetRawData() const {
177 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
178 return input_file_ptr_->data() + start_;
179}
180
181const uint8_t * ImageChunk::DataForPatch() const {
182 if (type_ == CHUNK_DEFLATE) {
183 return uncompressed_data_.data();
184 }
185 return GetRawData();
186}
187
188size_t ImageChunk::DataLengthForPatch() const {
189 if (type_ == CHUNK_DEFLATE) {
190 return uncompressed_data_.size();
191 }
192 return raw_data_len_;
193}
194
195bool ImageChunk::operator==(const ImageChunk& other) const {
196 if (type_ != other.type_) {
197 return false;
198 }
199 return (raw_data_len_ == other.raw_data_len_ &&
200 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
201}
202
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800203void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800204 uncompressed_data_ = std::move(data);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800205}
206
207bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
208 if (type_ != CHUNK_DEFLATE) {
209 return false;
210 }
211 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
212 return true;
213}
214
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800215void ImageChunk::ChangeDeflateChunkToNormal() {
216 if (type_ != CHUNK_DEFLATE) return;
217 type_ = CHUNK_NORMAL;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700218 // No need to clear the entry name.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800219 uncompressed_data_.clear();
220}
221
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800222bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
223 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
224 return false;
225 }
226 return (other.start_ == start_ + raw_data_len_);
227}
228
229void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
230 CHECK(IsAdjacentNormal(other));
231 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
232}
233
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700234bool ImageChunk::MakePatch(const ImageChunk& tgt, const ImageChunk& src,
235 std::vector<uint8_t>* patch_data, saidx_t** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700236#if defined(__ANDROID__)
237 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
238#else
239 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
240#endif
241
242 int fd = mkstemp(ptemp);
243 if (fd == -1) {
244 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
245 return false;
246 }
247 close(fd);
248
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700249 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
250 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700251 if (r != 0) {
252 printf("bsdiff() failed: %d\n", r);
253 return false;
254 }
255
256 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
257 if (patch_fd == -1) {
258 printf("failed to open %s: %s\n", ptemp, strerror(errno));
259 return false;
260 }
261 struct stat st;
262 if (fstat(patch_fd, &st) != 0) {
263 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
264 return false;
265 }
266
267 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700268
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700269 patch_data->resize(sz);
270 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
271 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
272 unlink(ptemp);
273 return false;
274 }
275
276 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700277
278 return true;
279}
280
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800281bool ImageChunk::ReconstructDeflateChunk() {
282 if (type_ != CHUNK_DEFLATE) {
283 printf("attempt to reconstruct non-deflate chunk\n");
284 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800285 }
286
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700287 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
288 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800289 for (int level = 6; level <= 9; level += 3) {
290 if (TryReconstruction(level)) {
291 compress_level_ = level;
292 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800293 }
294 }
Doug Zongker512536a2010-02-17 16:11:44 -0800295
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800296 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800297}
298
299/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700300 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
301 * in the chunk, and checks that it matches exactly the compressed data we started with (also
302 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800303 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800304bool ImageChunk::TryReconstruction(int level) {
305 z_stream strm;
306 strm.zalloc = Z_NULL;
307 strm.zfree = Z_NULL;
308 strm.opaque = Z_NULL;
309 strm.avail_in = uncompressed_data_.size();
310 strm.next_in = uncompressed_data_.data();
311 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
312 if (ret < 0) {
313 printf("failed to initialize deflate: %d\n", ret);
314 return false;
315 }
316
317 std::vector<uint8_t> buffer(BUFFER_SIZE);
318 size_t offset = 0;
319 do {
320 strm.avail_out = buffer.size();
321 strm.next_out = buffer.data();
322 ret = deflate(&strm, Z_FINISH);
323 if (ret < 0) {
324 printf("failed to deflate: %d\n", ret);
325 return false;
326 }
327
328 size_t compressed_size = buffer.size() - strm.avail_out;
329 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
330 // mismatch; data isn't the same.
331 deflateEnd(&strm);
332 return false;
333 }
334 offset += compressed_size;
335 } while (ret != Z_STREAM_END);
336 deflateEnd(&strm);
337
338 if (offset != raw_data_len_) {
339 // mismatch; ran out of data before we should have.
340 return false;
341 }
342 return true;
343}
344
Tianjie Xu57dd9612017-08-17 17:50:56 -0700345PatchChunk::PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
346 : type_(tgt.GetType()),
347 source_start_(src.GetStartOffset()),
348 source_len_(src.GetRawDataLength()),
349 source_uncompressed_len_(src.DataLengthForPatch()),
350 target_start_(tgt.GetStartOffset()),
351 target_len_(tgt.GetRawDataLength()),
352 target_uncompressed_len_(tgt.DataLengthForPatch()),
353 target_compress_level_(tgt.GetCompressLevel()),
354 data_(std::move(data)) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700355
Tianjie Xu57dd9612017-08-17 17:50:56 -0700356// Construct a CHUNK_RAW patch from the target data directly.
357PatchChunk::PatchChunk(const ImageChunk& tgt)
358 : type_(CHUNK_RAW),
359 source_start_(0),
360 source_len_(0),
361 source_uncompressed_len_(0),
362 target_start_(tgt.GetStartOffset()),
363 target_len_(tgt.GetRawDataLength()),
364 target_uncompressed_len_(tgt.DataLengthForPatch()),
365 target_compress_level_(tgt.GetCompressLevel()),
366 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700367
368// Return true if raw data is smaller than the patch size.
369bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
370 size_t target_len = tgt.GetRawDataLength();
371 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
372}
373
374// Header size:
375// header_type 4 bytes
376// CHUNK_NORMAL 8*3 = 24 bytes
377// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
378// CHUNK_RAW 4 bytes + patch_size
379size_t PatchChunk::GetHeaderSize() const {
380 switch (type_) {
381 case CHUNK_NORMAL:
382 return 4 + 8 * 3;
383 case CHUNK_DEFLATE:
384 return 4 + 8 * 5 + 4 * 5;
385 case CHUNK_RAW:
386 return 4 + 4 + data_.size();
387 default:
388 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
389 return 0;
390 }
391}
392
393// Return the offset of the next patch into the patch data.
394size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
395 Write4(fd, type_);
396 switch (type_) {
397 case CHUNK_NORMAL:
398 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
399 Write8(fd, static_cast<int64_t>(source_start_));
400 Write8(fd, static_cast<int64_t>(source_len_));
401 Write8(fd, static_cast<int64_t>(offset));
402 return offset + data_.size();
403 case CHUNK_DEFLATE:
404 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
405 Write8(fd, static_cast<int64_t>(source_start_));
406 Write8(fd, static_cast<int64_t>(source_len_));
407 Write8(fd, static_cast<int64_t>(offset));
408 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
409 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
410 Write4(fd, target_compress_level_);
411 Write4(fd, ImageChunk::METHOD);
412 Write4(fd, ImageChunk::WINDOWBITS);
413 Write4(fd, ImageChunk::MEMLEVEL);
414 Write4(fd, ImageChunk::STRATEGY);
415 return offset + data_.size();
416 case CHUNK_RAW:
417 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
418 Write4(fd, static_cast<int32_t>(data_.size()));
419 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
420 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
421 }
422 return offset;
423 default:
424 CHECK(false) << "unexpected chunk type: " << type_;
425 return offset;
426 }
427}
428
429// Write the contents of |patch_chunks| to |patch_fd|.
430bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
431 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
432 // the offset of each bsdiff patch within the file.
433 size_t total_header_size = 12;
434 for (const auto& patch : patch_chunks) {
435 total_header_size += patch.GetHeaderSize();
436 }
437
438 size_t offset = total_header_size;
439
440 // Write out the headers.
441 if (!android::base::WriteStringToFd("IMGDIFF2", patch_fd)) {
442 printf("failed to write \"IMGDIFF2\": %s\n", strerror(errno));
443 return false;
444 }
445
446 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
447 for (size_t i = 0; i < patch_chunks.size(); ++i) {
448 printf("chunk %zu: ", i);
449 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
450 }
451
452 // Append each chunk's bsdiff patch, in order.
453 for (const auto& patch : patch_chunks) {
454 if (patch.type_ == CHUNK_RAW) {
455 continue;
456 }
457 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
458 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
459 return false;
460 }
461 }
462
463 return true;
464}
465
Tianjie Xu57dd9612017-08-17 17:50:56 -0700466ImageChunk& Image::operator[](size_t i) {
467 CHECK_LT(i, chunks_.size());
468 return chunks_[i];
469}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700470
Tianjie Xu57dd9612017-08-17 17:50:56 -0700471const ImageChunk& Image::operator[](size_t i) const {
472 CHECK_LT(i, chunks_.size());
473 return chunks_[i];
474}
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700475
476void Image::MergeAdjacentNormalChunks() {
477 size_t merged_last = 0, cur = 0;
478 while (cur < chunks_.size()) {
479 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
480 // length of the current normal chunk.
481 size_t to_check = cur + 1;
482 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
483 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
484 to_check++;
485 }
486
487 if (merged_last != cur) {
488 chunks_[merged_last] = std::move(chunks_[cur]);
489 }
490 merged_last++;
491 cur = to_check;
492 }
493 if (merged_last < chunks_.size()) {
494 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
495 }
496}
497
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700498void Image::DumpChunks() const {
499 std::string type = is_source_ ? "source" : "target";
500 printf("Dumping chunks for %s\n", type.c_str());
501 for (size_t i = 0; i < chunks_.size(); ++i) {
502 printf("chunk %zu: ", i);
503 chunks_[i].Dump();
504 }
505}
506
507bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
508 CHECK(file_content != nullptr);
509
510 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
511 if (fd == -1) {
512 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
513 return false;
514 }
515 struct stat st;
516 if (fstat(fd, &st) != 0) {
517 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
518 return false;
519 }
520
521 size_t sz = static_cast<size_t>(st.st_size);
522 file_content->resize(sz);
523 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
524 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
525 return false;
526 }
527 fd.reset();
528
529 return true;
530}
531
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700532bool ZipModeImage::Initialize(const std::string& filename) {
533 if (!ReadFile(filename, &file_content_)) {
534 return false;
535 }
536
537 // Omit the trailing zeros before we pass the file to ziparchive handler.
538 size_t zipfile_size;
539 if (!GetZipFileSize(&zipfile_size)) {
540 printf("failed to parse the actual size of %s\n", filename.c_str());
541 return false;
542 }
543 ZipArchiveHandle handle;
544 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
545 filename.c_str(), &handle);
546 if (err != 0) {
547 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
548 CloseArchive(handle);
549 return false;
550 }
551
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700552 if (!InitializeChunks(filename, handle)) {
553 CloseArchive(handle);
554 return false;
555 }
556
557 CloseArchive(handle);
558 return true;
559}
560
561// Iterate the zip entries and compose the image chunks accordingly.
562bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
563 void* cookie;
564 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
565 if (ret != 0) {
566 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
567 return false;
568 }
569
570 // Create a list of deflated zip entries, sorted by offset.
571 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
572 ZipString name;
573 ZipEntry entry;
574 while ((ret = Next(cookie, &entry, &name)) == 0) {
575 if (entry.method == kCompressDeflated) {
576 std::string entry_name(name.name, name.name + name.name_length);
577 temp_entries.emplace_back(entry_name, entry);
578 }
579 }
580
581 if (ret != -1) {
582 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
583 return false;
584 }
585 std::sort(temp_entries.begin(), temp_entries.end(),
586 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
587
588 EndIteration(cookie);
589
590 // For source chunks, we don't need to compose chunks for the metadata.
591 if (is_source_) {
592 for (auto& entry : temp_entries) {
593 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
594 printf("Failed to add %s to source chunks\n", entry.first.c_str());
595 return false;
596 }
597 }
598 return true;
599 }
600
601 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
602 // deflate entries as CHUNK_NORMAL.
603 size_t pos = 0;
604 size_t nextentry = 0;
605 while (pos < file_content_.size()) {
606 if (nextentry < temp_entries.size() &&
607 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
608 // Add the next zip entry.
609 std::string entry_name = temp_entries[nextentry].first;
610 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
611 printf("Failed to add %s to target chunks\n", entry_name.c_str());
612 return false;
613 }
614
615 pos += temp_entries[nextentry].second.compressed_length;
616 ++nextentry;
617 continue;
618 }
619
620 // Use a normal chunk to take all the data up to the start of the next entry.
621 size_t raw_data_len;
622 if (nextentry < temp_entries.size()) {
623 raw_data_len = temp_entries[nextentry].second.offset - pos;
624 } else {
625 raw_data_len = file_content_.size() - pos;
626 }
627 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
628
629 pos += raw_data_len;
630 }
631
632 return true;
633}
634
635bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
636 ZipEntry* entry) {
637 size_t compressed_len = entry->compressed_length;
638 if (entry->method == kCompressDeflated) {
639 size_t uncompressed_len = entry->uncompressed_length;
640 std::vector<uint8_t> uncompressed_data(uncompressed_len);
641 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
642 if (ret != 0) {
643 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
644 ErrorCodeString(ret));
645 return false;
646 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700647 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700648 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700649 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700650 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700651 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700652 }
653
654 return true;
655}
656
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800657// EOCD record
658// offset 0: signature 0x06054b50, 4 bytes
659// offset 4: number of this disk, 2 bytes
660// ...
661// offset 20: comment length, 2 bytes
662// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700663bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
664 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800665 printf("file is too small to be a zip file\n");
666 return false;
667 }
668
669 // Look for End of central directory record of the zip file, and calculate the actual
670 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700671 for (int i = file_content_.size() - 22; i >= 0; i--) {
672 if (file_content_[i] == 0x50) {
673 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800674 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700675 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800676
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700677 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800678 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700679 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800680 *input_file_size = file_size;
681 return true;
682 }
683 }
684 }
685
686 // EOCD not found, this file is likely not a valid zip file.
687 return false;
688}
689
Tianjie Xu57dd9612017-08-17 17:50:56 -0700690ImageChunk ZipModeImage::PseudoSource() const {
691 CHECK(is_source_);
692 return ImageChunk(CHUNK_NORMAL, 0, &file_content_, file_content_.size());
693}
694
695const ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) const {
696 if (name.empty()) {
697 return nullptr;
698 }
699 for (auto& chunk : chunks_) {
700 if ((chunk.GetType() == CHUNK_DEFLATE || find_normal) && chunk.GetEntryName() == name) {
701 return &chunk;
702 }
703 }
704 return nullptr;
705}
706
707ImageChunk* ZipModeImage::FindChunkByName(const std::string& name, bool find_normal) {
708 return const_cast<ImageChunk*>(
709 static_cast<const ZipModeImage*>(this)->FindChunkByName(name, find_normal));
710}
711
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700712bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
713 for (auto& tgt_chunk : *tgt_image) {
714 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800715 continue;
716 }
717
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700718 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
719 if (src_chunk == nullptr) {
720 tgt_chunk.ChangeDeflateChunkToNormal();
721 } else if (tgt_chunk == *src_chunk) {
722 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
723 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
724 // patch to the compressed data, rather than uncompressing and recompressing to apply the
725 // trivial patch to the uncompressed data.
726 tgt_chunk.ChangeDeflateChunkToNormal();
727 src_chunk->ChangeDeflateChunkToNormal();
728 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
729 // We cannot recompress the data and get exactly the same bits as are in the input target
730 // image. Treat the chunk as a normal non-deflated chunk.
731 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
732 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800733
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700734 tgt_chunk.ChangeDeflateChunkToNormal();
735 src_chunk->ChangeDeflateChunkToNormal();
736 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800737 }
738
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700739 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
740 // filename, and normal chunks are patched using the entire source file as the source.
741 tgt_image->MergeAdjacentNormalChunks();
742 tgt_image->DumpChunks();
Tianjie Xu12b90552017-03-07 14:44:14 -0800743
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700744 return true;
745}
746
747bool ZipModeImage::GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
748 const std::string& patch_name) {
749 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
750 std::vector<PatchChunk> patch_chunks;
751 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700752
753 saidx_t* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700754 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
755 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700756
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700757 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
758 patch_chunks.emplace_back(tgt_chunk);
759 continue;
760 }
761
762 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
763 ? nullptr
764 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
765
766 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700767 saidx_t** bsdiff_cache_ptr = (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
768
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700769 std::vector<uint8_t> patch_data;
770 if (!ImageChunk::MakePatch(tgt_chunk, src_ref, &patch_data, bsdiff_cache_ptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700771 printf("Failed to generate patch, name: %s\n", tgt_chunk.GetEntryName().c_str());
772 return false;
773 }
774
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700775 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700776 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700777
778 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
779 patch_chunks.emplace_back(tgt_chunk);
780 } else {
781 patch_chunks.emplace_back(tgt_chunk, src_ref, std::move(patch_data));
782 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800783 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700784 free(bsdiff_cache);
785
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700786 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
787
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700788 android::base::unique_fd patch_fd(
789 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
790 if (patch_fd == -1) {
791 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800792 return false;
793 }
794
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700795 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700796}
797
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700798bool ImageModeImage::Initialize(const std::string& filename) {
799 if (!ReadFile(filename, &file_content_)) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800800 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800801 }
Doug Zongker512536a2010-02-17 16:11:44 -0800802
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700803 size_t sz = file_content_.size();
Doug Zongker512536a2010-02-17 16:11:44 -0800804 size_t pos = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700805 while (pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800806 // 0x00 no header flags, 0x08 deflate compression, 0x1f8b gzip magic number
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700807 if (sz - pos >= 4 && get_unaligned<uint32_t>(file_content_.data() + pos) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -0800808 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +0200809 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800810
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800811 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
812 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700813 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, sz - pos);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800814 break;
815 }
Doug Zongker512536a2010-02-17 16:11:44 -0800816
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800817 // We need three chunks for the deflated image in total, one normal chunk for the header,
818 // one deflated chunk for the body, and another normal chunk for the footer.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700819 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_HEADER_LEN);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800820 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -0800821
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800822 // We must decompress this chunk in order to discover where it ends, and so we can update
823 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -0800824
825 z_stream strm;
826 strm.zalloc = Z_NULL;
827 strm.zfree = Z_NULL;
828 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -0700829 strm.avail_in = sz - pos;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700830 strm.next_in = file_content_.data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800831
832 // -15 means we are decoding a 'raw' deflate stream; zlib will
833 // not expect zlib headers.
834 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -0800835 if (ret < 0) {
836 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800837 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -0800838 }
Doug Zongker512536a2010-02-17 16:11:44 -0800839
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800840 size_t allocated = BUFFER_SIZE;
841 std::vector<uint8_t> uncompressed_data(allocated);
842 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800843 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800844 strm.avail_out = allocated - uncompressed_len;
845 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800846 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +0200847 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800848 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -0800849 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800850 break;
Johan Redestigc68bd342015-04-14 21:20:06 +0200851 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800852 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -0800853 if (strm.avail_out == 0) {
854 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800855 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -0800856 }
857 } while (ret != Z_STREAM_END);
858
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800859 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800860 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800861
862 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800863 continue;
864 }
865
Tianjie Xu14ebc1e2017-07-05 12:04:07 -0700866 // The footer contains the size of the uncompressed data. Double-check to make sure that it
867 // matches the size of the data we got when we actually did the decompression.
868 size_t footer_index = pos + raw_data_len + GZIP_FOOTER_LEN - 4;
869 if (sz - footer_index < 4) {
870 printf("Warning: invalid footer position; treating as a nomal chunk\n");
871 continue;
872 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700873 size_t footer_size = get_unaligned<uint32_t>(file_content_.data() + footer_index);
Tianjie Xu14ebc1e2017-07-05 12:04:07 -0700874 if (footer_size != uncompressed_len) {
875 printf("Warning: footer size %zu != decompressed size %zu; treating as a nomal chunk\n",
876 footer_size, uncompressed_len);
877 continue;
878 }
879
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700880 ImageChunk body(CHUNK_DEFLATE, pos, &file_content_, raw_data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800881 uncompressed_data.resize(uncompressed_len);
882 body.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700883 chunks_.push_back(std::move(body));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800884
885 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800886
887 // create a normal chunk for the footer
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700888 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -0800889
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800890 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -0800891 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800892 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
893 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -0800894
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800895 // Scan forward until we find a gzip header.
896 size_t data_len = 0;
897 while (data_len + pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800898 if (data_len + pos + 4 <= sz &&
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700899 get_unaligned<uint32_t>(file_content_.data() + pos + data_len) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -0800900 break;
901 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800902 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -0800903 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700904 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800905
906 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800907 }
908 }
909
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800910 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800911}
912
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700913bool ImageModeImage::SetBonusData(const std::vector<uint8_t>& bonus_data) {
914 CHECK(is_source_);
915 if (chunks_.size() < 2 || !chunks_[1].SetBonusData(bonus_data)) {
916 printf("Failed to set bonus data\n");
917 DumpChunks();
918 return false;
919 }
920
921 printf(" using %zu bytes of bonus data\n", bonus_data.size());
922 return true;
923}
924
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700925// In Image Mode, verify that the source and target images have the same chunk structure (ie, the
926// same sequence of deflate and normal chunks).
927bool ImageModeImage::CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image) {
928 // In image mode, merge the gzip header and footer in with any adjacent normal chunks.
929 tgt_image->MergeAdjacentNormalChunks();
930 src_image->MergeAdjacentNormalChunks();
Doug Zongker512536a2010-02-17 16:11:44 -0800931
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700932 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
933 printf("source and target don't have same number of chunks!\n");
934 tgt_image->DumpChunks();
935 src_image->DumpChunks();
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800936 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +0200937 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700938 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700939 if ((*tgt_image)[i].GetType() != (*src_image)[i].GetType()) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700940 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
941 tgt_image->DumpChunks();
942 src_image->DumpChunks();
943 return false;
944 }
Doug Zongker512536a2010-02-17 16:11:44 -0800945 }
946
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700947 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700948 auto& tgt_chunk = (*tgt_image)[i];
949 auto& src_chunk = (*src_image)[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700950 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
951 continue;
952 }
953
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700954 // If two deflate chunks are identical treat them as normal chunks.
955 if (tgt_chunk == src_chunk) {
956 tgt_chunk.ChangeDeflateChunkToNormal();
957 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700958 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
959 // We cannot recompress the data and get exactly the same bits as are in the input target
960 // image, fall back to normal
961 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
962 tgt_chunk.GetEntryName().c_str());
963 tgt_chunk.ChangeDeflateChunkToNormal();
964 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700965 }
Doug Zongker512536a2010-02-17 16:11:44 -0800966 }
967
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700968 // For images, we need to maintain the parallel structure of the chunk lists, so do the merging
969 // in both the source and target lists.
970 tgt_image->MergeAdjacentNormalChunks();
971 src_image->MergeAdjacentNormalChunks();
972 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
973 // This shouldn't happen.
974 printf("merging normal chunks went awry\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800975 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800976 }
Doug Zongker512536a2010-02-17 16:11:44 -0800977
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800978 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800979}
980
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700981// In image mode, generate patches against the given source chunks and bonus_data; write the
982// result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700983bool ImageModeImage::GeneratePatches(const ImageModeImage& tgt_image,
984 const ImageModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700985 const std::string& patch_name) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700986 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
987 std::vector<PatchChunk> patch_chunks;
988 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700989
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700990 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
991 const auto& tgt_chunk = tgt_image[i];
992 const auto& src_chunk = src_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700993
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700994 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
995 patch_chunks.emplace_back(tgt_chunk);
996 continue;
Doug Zongker512536a2010-02-17 16:11:44 -0800997 }
998
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700999 std::vector<uint8_t> patch_data;
1000 if (!ImageChunk::MakePatch(tgt_chunk, src_chunk, &patch_data, nullptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001001 printf("Failed to generate patch for target chunk %zu: ", i);
1002 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001003 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001004 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001005 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001006
1007 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
1008 patch_chunks.emplace_back(tgt_chunk);
1009 } else {
1010 patch_chunks.emplace_back(tgt_chunk, src_chunk, std::move(patch_data));
1011 }
Doug Zongker512536a2010-02-17 16:11:44 -08001012 }
Doug Zongker512536a2010-02-17 16:11:44 -08001013
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001014 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1015
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001016 android::base::unique_fd patch_fd(
1017 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1018 if (patch_fd == -1) {
1019 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1020 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001021 }
Doug Zongker512536a2010-02-17 16:11:44 -08001022
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001023 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Doug Zongker512536a2010-02-17 16:11:44 -08001024}
1025
Tao Bao97555da2016-12-15 10:15:06 -08001026int imgdiff(int argc, const char** argv) {
1027 bool zip_mode = false;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001028 std::vector<uint8_t> bonus_data;
Tianjie Xu12b90552017-03-07 14:44:14 -08001029
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001030 int opt;
1031 optind = 1; // Reset the getopt state so that we can call it multiple times for test.
Doug Zongkera3ccba62012-08-20 15:28:02 -07001032
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001033 while ((opt = getopt(argc, const_cast<char**>(argv), "zb:")) != -1) {
1034 switch (opt) {
1035 case 'z':
1036 zip_mode = true;
1037 break;
1038 case 'b': {
1039 android::base::unique_fd fd(open(optarg, O_RDONLY));
1040 if (fd == -1) {
1041 printf("failed to open bonus file %s: %s\n", optarg, strerror(errno));
1042 return 1;
1043 }
1044 struct stat st;
1045 if (fstat(fd, &st) != 0) {
1046 printf("failed to stat bonus file %s: %s\n", optarg, strerror(errno));
1047 return 1;
1048 }
1049
1050 size_t bonus_size = st.st_size;
1051 bonus_data.resize(bonus_size);
1052 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
1053 printf("failed to read bonus file %s: %s\n", optarg, strerror(errno));
1054 return 1;
1055 }
1056 break;
1057 }
1058 default:
1059 printf("unexpected opt: %s\n", optarg);
1060 return 2;
1061 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001062 }
1063
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001064 if (argc - optind != 3) {
1065 printf("usage: %s [-z] [-b <bonus-file>] <src-img> <tgt-img> <patch-file>\n", argv[0]);
Doug Zongkera3ccba62012-08-20 15:28:02 -07001066 return 2;
1067 }
Doug Zongker512536a2010-02-17 16:11:44 -08001068
Doug Zongker512536a2010-02-17 16:11:44 -08001069 if (zip_mode) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001070 ZipModeImage src_image(true);
1071 ZipModeImage tgt_image(false);
1072
1073 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001074 return 1;
1075 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001076 if (!tgt_image.Initialize(argv[optind + 1])) {
1077 return 1;
1078 }
1079
1080 if (!ZipModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
1081 return 1;
1082 }
1083 // Compute bsdiff patches for each chunk's data (the uncompressed data, in the case of
1084 // deflate chunks).
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001085 if (!ZipModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001086 return 1;
1087 }
1088 } else {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001089 ImageModeImage src_image(true);
1090 ImageModeImage tgt_image(false);
1091
1092 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001093 return 1;
1094 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001095 if (!tgt_image.Initialize(argv[optind + 1])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001096 return 1;
1097 }
1098
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001099 if (!ImageModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
Doug Zongker512536a2010-02-17 16:11:44 -08001100 return 1;
1101 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001102
1103 if (!bonus_data.empty() && !src_image.SetBonusData(bonus_data)) {
1104 return 1;
1105 }
1106
1107 if (!ImageModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001108 return 1;
1109 }
1110 }
1111
Doug Zongker512536a2010-02-17 16:11:44 -08001112 return 0;
1113}