blob: a81e385a3e4cfd786b08ebba7e4c077f464949af [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>
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800143#include <ziparchive/zip_archive.h>
Tao Baod37ce8f2016-12-17 17:10:04 -0800144
Sen Jiang2fffcb12016-05-03 15:49:10 -0700145#include <bsdiff.h>
Tao Bao97555da2016-12-15 10:15:06 -0800146#include <zlib.h>
Sen Jiang2fffcb12016-05-03 15:49:10 -0700147
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800148using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800149
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800150static constexpr auto BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800151
Tianjie Xu12b90552017-03-07 14:44:14 -0800152// If we use this function to write the offset and length (type size_t), their values should not
153// exceed 2^63; because the signed bit will be casted away.
154static inline bool Write8(int fd, int64_t value) {
155 return android::base::WriteFully(fd, &value, sizeof(int64_t));
156}
157
158// Similarly, the value should not exceed 2^31 if we are casting from size_t (e.g. target chunk
159// size).
160static inline bool Write4(int fd, int32_t value) {
161 return android::base::WriteFully(fd, &value, sizeof(int32_t));
162}
163
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800164class ImageChunk {
165 public:
166 static constexpr auto WINDOWBITS = -15; // 32kb window; negative to indicate a raw stream.
167 static constexpr auto MEMLEVEL = 8; // the default value.
168 static constexpr auto METHOD = Z_DEFLATED;
169 static constexpr auto STRATEGY = Z_DEFAULT_STRATEGY;
170
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700171 ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content, size_t raw_data_len,
172 std::string entry_name = {})
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800173 : type_(type),
174 start_(start),
175 input_file_ptr_(file_content),
176 raw_data_len_(raw_data_len),
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800177 compress_level_(6),
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700178 entry_name_(std::move(entry_name)) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800179 CHECK(file_content != nullptr) << "input file container can't be nullptr";
180 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800181
182 int GetType() const {
183 return type_;
184 }
185 size_t GetRawDataLength() const {
186 return raw_data_len_;
187 }
188 const std::string& GetEntryName() const {
189 return entry_name_;
190 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700191 size_t GetStartOffset() const {
192 return start_;
193 }
194 int GetCompressLevel() const {
195 return compress_level_;
196 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800197
198 // CHUNK_DEFLATE will return the uncompressed data for diff, while other types will simply return
199 // the raw data.
200 const uint8_t * DataForPatch() const;
201 size_t DataLengthForPatch() const;
202
203 void Dump() const {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700204 printf("type: %d, start: %zu, len: %zu, name: %s\n", type_, start_, DataLengthForPatch(),
205 entry_name_.c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800206 }
207
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800208 void SetUncompressedData(std::vector<uint8_t> data);
209 bool SetBonusData(const std::vector<uint8_t>& bonus_data);
210
211 bool operator==(const ImageChunk& other) const;
212 bool operator!=(const ImageChunk& other) const {
213 return !(*this == other);
214 }
215
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800216 /*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700217 * Cause a gzip chunk to be treated as a normal chunk (ie, as a blob of uninterpreted data).
218 * The resulting patch will likely be about as big as the target file, but it lets us handle
219 * the case of images where some gzip chunks are reconstructible but others aren't (by treating
220 * the ones that aren't as normal chunks).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800221 */
222 void ChangeDeflateChunkToNormal();
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800223
224 /*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700225 * Verify that we can reproduce exactly the same compressed data that we started with. Sets the
226 * level, method, windowBits, memLevel, and strategy fields in the chunk to the encoding
227 * parameters needed to produce the right output.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800228 */
229 bool ReconstructDeflateChunk();
230 bool IsAdjacentNormal(const ImageChunk& other) const;
231 void MergeAdjacentNormal(const ImageChunk& other);
232
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700233 /*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700234 * Compute a bsdiff patch between |src| and |tgt|; Store the result in the patch_data.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700235 * |bsdiff_cache| can be used to cache the suffix array if the same |src| chunk is used
236 * repeatedly, pass nullptr if not needed.
237 */
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700238 static bool MakePatch(const ImageChunk& tgt, const ImageChunk& src,
239 std::vector<uint8_t>* patch_data, saidx_t** bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700240
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800241 private:
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700242 const uint8_t* GetRawData() const;
243 bool TryReconstruction(int level);
244
Tianjie Xu12b90552017-03-07 14:44:14 -0800245 int type_; // CHUNK_NORMAL, CHUNK_DEFLATE, CHUNK_RAW
246 size_t start_; // offset of chunk in the original input file
247 const std::vector<uint8_t>* input_file_ptr_; // ptr to the full content of original input file
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800248 size_t raw_data_len_;
Doug Zongker512536a2010-02-17 16:11:44 -0800249
Doug Zongker512536a2010-02-17 16:11:44 -0800250 // deflate encoder parameters
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800251 int compress_level_;
Doug Zongker512536a2010-02-17 16:11:44 -0800252
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700253 // --- for CHUNK_DEFLATE chunks only: ---
254 std::vector<uint8_t> uncompressed_data_;
255 std::string entry_name_; // used for zip entries
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800256};
Doug Zongker512536a2010-02-17 16:11:44 -0800257
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800258const uint8_t* ImageChunk::GetRawData() const {
259 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
260 return input_file_ptr_->data() + start_;
261}
262
263const uint8_t * ImageChunk::DataForPatch() const {
264 if (type_ == CHUNK_DEFLATE) {
265 return uncompressed_data_.data();
266 }
267 return GetRawData();
268}
269
270size_t ImageChunk::DataLengthForPatch() const {
271 if (type_ == CHUNK_DEFLATE) {
272 return uncompressed_data_.size();
273 }
274 return raw_data_len_;
275}
276
277bool ImageChunk::operator==(const ImageChunk& other) const {
278 if (type_ != other.type_) {
279 return false;
280 }
281 return (raw_data_len_ == other.raw_data_len_ &&
282 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
283}
284
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800285void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
Tianjie Xu12b90552017-03-07 14:44:14 -0800286 uncompressed_data_ = std::move(data);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800287}
288
289bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
290 if (type_ != CHUNK_DEFLATE) {
291 return false;
292 }
293 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
294 return true;
295}
296
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800297void ImageChunk::ChangeDeflateChunkToNormal() {
298 if (type_ != CHUNK_DEFLATE) return;
299 type_ = CHUNK_NORMAL;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700300 // No need to clear the entry name.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800301 uncompressed_data_.clear();
302}
303
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800304bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
305 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
306 return false;
307 }
308 return (other.start_ == start_ + raw_data_len_);
309}
310
311void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
312 CHECK(IsAdjacentNormal(other));
313 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
314}
315
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700316bool ImageChunk::MakePatch(const ImageChunk& tgt, const ImageChunk& src,
317 std::vector<uint8_t>* patch_data, saidx_t** bsdiff_cache) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700318#if defined(__ANDROID__)
319 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
320#else
321 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
322#endif
323
324 int fd = mkstemp(ptemp);
325 if (fd == -1) {
326 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
327 return false;
328 }
329 close(fd);
330
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700331 int r = bsdiff::bsdiff(src.DataForPatch(), src.DataLengthForPatch(), tgt.DataForPatch(),
332 tgt.DataLengthForPatch(), ptemp, bsdiff_cache);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700333 if (r != 0) {
334 printf("bsdiff() failed: %d\n", r);
335 return false;
336 }
337
338 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
339 if (patch_fd == -1) {
340 printf("failed to open %s: %s\n", ptemp, strerror(errno));
341 return false;
342 }
343 struct stat st;
344 if (fstat(patch_fd, &st) != 0) {
345 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
346 return false;
347 }
348
349 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700350
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700351 patch_data->resize(sz);
352 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
353 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
354 unlink(ptemp);
355 return false;
356 }
357
358 unlink(ptemp);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700359
360 return true;
361}
362
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800363bool ImageChunk::ReconstructDeflateChunk() {
364 if (type_ != CHUNK_DEFLATE) {
365 printf("attempt to reconstruct non-deflate chunk\n");
366 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800367 }
368
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700369 // We only check two combinations of encoder parameters: level 6 (the default) and level 9
370 // (the maximum).
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800371 for (int level = 6; level <= 9; level += 3) {
372 if (TryReconstruction(level)) {
373 compress_level_ = level;
374 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800375 }
376 }
Doug Zongker512536a2010-02-17 16:11:44 -0800377
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800378 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800379}
380
381/*
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700382 * Takes the uncompressed data stored in the chunk, compresses it using the zlib parameters stored
383 * in the chunk, and checks that it matches exactly the compressed data we started with (also
384 * stored in the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800385 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800386bool ImageChunk::TryReconstruction(int level) {
387 z_stream strm;
388 strm.zalloc = Z_NULL;
389 strm.zfree = Z_NULL;
390 strm.opaque = Z_NULL;
391 strm.avail_in = uncompressed_data_.size();
392 strm.next_in = uncompressed_data_.data();
393 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
394 if (ret < 0) {
395 printf("failed to initialize deflate: %d\n", ret);
396 return false;
397 }
398
399 std::vector<uint8_t> buffer(BUFFER_SIZE);
400 size_t offset = 0;
401 do {
402 strm.avail_out = buffer.size();
403 strm.next_out = buffer.data();
404 ret = deflate(&strm, Z_FINISH);
405 if (ret < 0) {
406 printf("failed to deflate: %d\n", ret);
407 return false;
408 }
409
410 size_t compressed_size = buffer.size() - strm.avail_out;
411 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
412 // mismatch; data isn't the same.
413 deflateEnd(&strm);
414 return false;
415 }
416 offset += compressed_size;
417 } while (ret != Z_STREAM_END);
418 deflateEnd(&strm);
419
420 if (offset != raw_data_len_) {
421 // mismatch; ran out of data before we should have.
422 return false;
423 }
424 return true;
425}
426
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700427// PatchChunk stores the patch data between a source chunk and a target chunk. It also keeps track
428// of the metadata of src&tgt chunks (e.g. offset, raw data length, uncompressed data length).
429class PatchChunk {
430 public:
431 PatchChunk(const ImageChunk& tgt, const ImageChunk& src, std::vector<uint8_t> data)
432 : type_(tgt.GetType()),
433 source_start_(src.GetStartOffset()),
434 source_len_(src.GetRawDataLength()),
435 source_uncompressed_len_(src.DataLengthForPatch()),
436 target_start_(tgt.GetStartOffset()),
437 target_len_(tgt.GetRawDataLength()),
438 target_uncompressed_len_(tgt.DataLengthForPatch()),
439 target_compress_level_(tgt.GetCompressLevel()),
440 data_(std::move(data)) {}
441
442 // Construct a CHUNK_RAW patch from the target data directly.
443 explicit PatchChunk(const ImageChunk& tgt)
444 : type_(CHUNK_RAW),
445 source_start_(0),
446 source_len_(0),
447 source_uncompressed_len_(0),
448 target_start_(tgt.GetStartOffset()),
449 target_len_(tgt.GetRawDataLength()),
450 target_uncompressed_len_(tgt.DataLengthForPatch()),
451 target_compress_level_(tgt.GetCompressLevel()),
452 data_(tgt.DataForPatch(), tgt.DataForPatch() + tgt.DataLengthForPatch()) {}
453
454 // Return true if raw data size is smaller than the patch size.
455 static bool RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size);
456
457 static bool WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd);
458
459 private:
460 size_t GetHeaderSize() const;
461 size_t WriteHeaderToFd(int fd, size_t offset) const;
462
463 // The patch chunk type is the same as the target chunk type. The only exception is we change
464 // the |type_| to CHUNK_RAW if target length is smaller than the patch size.
465 int type_;
466
467 size_t source_start_;
468 size_t source_len_;
469 size_t source_uncompressed_len_;
470
471 size_t target_start_; // offset of the target chunk within the target file
472 size_t target_len_;
473 size_t target_uncompressed_len_;
474 size_t target_compress_level_; // the deflate compression level of the target chunk.
475
476 std::vector<uint8_t> data_; // storage for the patch data
477};
478
479// Return true if raw data is smaller than the patch size.
480bool PatchChunk::RawDataIsSmaller(const ImageChunk& tgt, size_t patch_size) {
481 size_t target_len = tgt.GetRawDataLength();
482 return (tgt.GetType() == CHUNK_NORMAL && (target_len <= 160 || target_len < patch_size));
483}
484
485// Header size:
486// header_type 4 bytes
487// CHUNK_NORMAL 8*3 = 24 bytes
488// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
489// CHUNK_RAW 4 bytes + patch_size
490size_t PatchChunk::GetHeaderSize() const {
491 switch (type_) {
492 case CHUNK_NORMAL:
493 return 4 + 8 * 3;
494 case CHUNK_DEFLATE:
495 return 4 + 8 * 5 + 4 * 5;
496 case CHUNK_RAW:
497 return 4 + 4 + data_.size();
498 default:
499 CHECK(false) << "unexpected chunk type: " << type_; // Should not reach here.
500 return 0;
501 }
502}
503
504// Return the offset of the next patch into the patch data.
505size_t PatchChunk::WriteHeaderToFd(int fd, size_t offset) const {
506 Write4(fd, type_);
507 switch (type_) {
508 case CHUNK_NORMAL:
509 printf("normal (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
510 Write8(fd, static_cast<int64_t>(source_start_));
511 Write8(fd, static_cast<int64_t>(source_len_));
512 Write8(fd, static_cast<int64_t>(offset));
513 return offset + data_.size();
514 case CHUNK_DEFLATE:
515 printf("deflate (%10zu, %10zu) %10zu\n", target_start_, target_len_, data_.size());
516 Write8(fd, static_cast<int64_t>(source_start_));
517 Write8(fd, static_cast<int64_t>(source_len_));
518 Write8(fd, static_cast<int64_t>(offset));
519 Write8(fd, static_cast<int64_t>(source_uncompressed_len_));
520 Write8(fd, static_cast<int64_t>(target_uncompressed_len_));
521 Write4(fd, target_compress_level_);
522 Write4(fd, ImageChunk::METHOD);
523 Write4(fd, ImageChunk::WINDOWBITS);
524 Write4(fd, ImageChunk::MEMLEVEL);
525 Write4(fd, ImageChunk::STRATEGY);
526 return offset + data_.size();
527 case CHUNK_RAW:
528 printf("raw (%10zu, %10zu)\n", target_start_, target_len_);
529 Write4(fd, static_cast<int32_t>(data_.size()));
530 if (!android::base::WriteFully(fd, data_.data(), data_.size())) {
531 CHECK(false) << "failed to write " << data_.size() << " bytes patch";
532 }
533 return offset;
534 default:
535 CHECK(false) << "unexpected chunk type: " << type_;
536 return offset;
537 }
538}
539
540// Write the contents of |patch_chunks| to |patch_fd|.
541bool PatchChunk::WritePatchDataToFd(const std::vector<PatchChunk>& patch_chunks, int patch_fd) {
542 // Figure out how big the imgdiff file header is going to be, so that we can correctly compute
543 // the offset of each bsdiff patch within the file.
544 size_t total_header_size = 12;
545 for (const auto& patch : patch_chunks) {
546 total_header_size += patch.GetHeaderSize();
547 }
548
549 size_t offset = total_header_size;
550
551 // Write out the headers.
552 if (!android::base::WriteStringToFd("IMGDIFF2", patch_fd)) {
553 printf("failed to write \"IMGDIFF2\": %s\n", strerror(errno));
554 return false;
555 }
556
557 Write4(patch_fd, static_cast<int32_t>(patch_chunks.size()));
558 for (size_t i = 0; i < patch_chunks.size(); ++i) {
559 printf("chunk %zu: ", i);
560 offset = patch_chunks[i].WriteHeaderToFd(patch_fd, offset);
561 }
562
563 // Append each chunk's bsdiff patch, in order.
564 for (const auto& patch : patch_chunks) {
565 if (patch.type_ == CHUNK_RAW) {
566 continue;
567 }
568 if (!android::base::WriteFully(patch_fd, patch.data_.data(), patch.data_.size())) {
569 printf("failed to write %zu bytes patch to patch_fd\n", patch.data_.size());
570 return false;
571 }
572 }
573
574 return true;
575}
576
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700577// Interface for zip_mode and image_mode images. We initialize the image from an input file and
578// split the file content into a list of image chunks.
579class Image {
580 public:
581 explicit Image(bool is_source) : is_source_(is_source) {}
582
583 virtual ~Image() {}
584
585 // Create a list of image chunks from input file.
586 virtual bool Initialize(const std::string& filename) = 0;
587
588 // Look for runs of adjacent normal chunks and compress them down into a single chunk. (Such
589 // runs can be produced when deflate chunks are changed to normal chunks.)
590 void MergeAdjacentNormalChunks();
591
592 // In zip mode, find the matching deflate source chunk by entry name. Search for normal chunks
593 // also if |find_normal| is true.
594 ImageChunk* FindChunkByName(const std::string& name, bool find_normal = false);
595
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700596 const ImageChunk* FindChunkByName(const std::string& name, bool find_normal = false) const;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700597
598 void DumpChunks() const;
599
600 // Non const iterators to access the stored ImageChunks.
601 std::vector<ImageChunk>::iterator begin() {
602 return chunks_.begin();
603 }
604
605 std::vector<ImageChunk>::iterator end() {
606 return chunks_.end();
607 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700608
609 ImageChunk& operator[](size_t i) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700610 CHECK_LT(i, chunks_.size());
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700611 return chunks_[i];
612 }
613
614 const ImageChunk& operator[](size_t i) const {
615 CHECK_LT(i, chunks_.size());
616 return chunks_[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700617 }
618
619 size_t NumOfChunks() const {
620 return chunks_.size();
621 }
622
623 protected:
624 bool ReadFile(const std::string& filename, std::vector<uint8_t>* file_content);
625
626 bool is_source_; // True if it's for source chunks.
627 std::vector<ImageChunk> chunks_; // Internal storage of ImageChunk.
628 std::vector<uint8_t> file_content_; // Store the whole input file in memory.
629};
630
631void Image::MergeAdjacentNormalChunks() {
632 size_t merged_last = 0, cur = 0;
633 while (cur < chunks_.size()) {
634 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
635 // length of the current normal chunk.
636 size_t to_check = cur + 1;
637 while (to_check < chunks_.size() && chunks_[cur].IsAdjacentNormal(chunks_[to_check])) {
638 chunks_[cur].MergeAdjacentNormal(chunks_[to_check]);
639 to_check++;
640 }
641
642 if (merged_last != cur) {
643 chunks_[merged_last] = std::move(chunks_[cur]);
644 }
645 merged_last++;
646 cur = to_check;
647 }
648 if (merged_last < chunks_.size()) {
649 chunks_.erase(chunks_.begin() + merged_last, chunks_.end());
650 }
651}
652
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700653const ImageChunk* Image::FindChunkByName(const std::string& name, bool find_normal) const {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700654 if (name.empty()) {
655 return nullptr;
656 }
657 for (auto& chunk : chunks_) {
658 if ((chunk.GetType() == CHUNK_DEFLATE || find_normal) && chunk.GetEntryName() == name) {
659 return &chunk;
660 }
661 }
662 return nullptr;
663}
664
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700665ImageChunk* Image::FindChunkByName(const std::string& name, bool find_normal) {
666 return const_cast<ImageChunk*>(
667 static_cast<const Image*>(this)->FindChunkByName(name, find_normal));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700668}
669
670void Image::DumpChunks() const {
671 std::string type = is_source_ ? "source" : "target";
672 printf("Dumping chunks for %s\n", type.c_str());
673 for (size_t i = 0; i < chunks_.size(); ++i) {
674 printf("chunk %zu: ", i);
675 chunks_[i].Dump();
676 }
677}
678
679bool Image::ReadFile(const std::string& filename, std::vector<uint8_t>* file_content) {
680 CHECK(file_content != nullptr);
681
682 android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
683 if (fd == -1) {
684 printf("failed to open \"%s\" %s\n", filename.c_str(), strerror(errno));
685 return false;
686 }
687 struct stat st;
688 if (fstat(fd, &st) != 0) {
689 printf("failed to stat \"%s\": %s\n", filename.c_str(), strerror(errno));
690 return false;
691 }
692
693 size_t sz = static_cast<size_t>(st.st_size);
694 file_content->resize(sz);
695 if (!android::base::ReadFully(fd, file_content->data(), sz)) {
696 printf("failed to read \"%s\" %s\n", filename.c_str(), strerror(errno));
697 return false;
698 }
699 fd.reset();
700
701 return true;
702}
703
704class ZipModeImage : public Image {
705 public:
706 explicit ZipModeImage(bool is_source) : Image(is_source) {}
707
708 bool Initialize(const std::string& filename) override;
709
710 const ImageChunk& PseudoSource() const {
711 CHECK(is_source_);
712 CHECK(pseudo_source_ != nullptr);
713 return *pseudo_source_;
714 }
715
716 // Verify that we can reconstruct the deflate chunks; also change the type to CHUNK_NORMAL if
717 // src and tgt are identical.
718 static bool CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image);
719
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700720 // Compute the patch between tgt & src images, and write the data into |patch_name|.
721 static bool GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700722 const std::string& patch_name);
723
724 private:
725 // Initialize image chunks based on the zip entries.
726 bool InitializeChunks(const std::string& filename, ZipArchiveHandle handle);
727 // Add the a zip entry to the list.
728 bool AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name, ZipEntry* entry);
729 // Return the real size of the zip file. (omit the trailing zeros that used for alignment)
730 bool GetZipFileSize(size_t* input_file_size);
731
732 // The pesudo source chunk for bsdiff if there's no match for the given target chunk. It's in
733 // fact the whole source file.
734 std::unique_ptr<ImageChunk> pseudo_source_;
735};
736
737bool ZipModeImage::Initialize(const std::string& filename) {
738 if (!ReadFile(filename, &file_content_)) {
739 return false;
740 }
741
742 // Omit the trailing zeros before we pass the file to ziparchive handler.
743 size_t zipfile_size;
744 if (!GetZipFileSize(&zipfile_size)) {
745 printf("failed to parse the actual size of %s\n", filename.c_str());
746 return false;
747 }
748 ZipArchiveHandle handle;
749 int err = OpenArchiveFromMemory(const_cast<uint8_t*>(file_content_.data()), zipfile_size,
750 filename.c_str(), &handle);
751 if (err != 0) {
752 printf("failed to open zip file %s: %s\n", filename.c_str(), ErrorCodeString(err));
753 CloseArchive(handle);
754 return false;
755 }
756
757 if (is_source_) {
758 pseudo_source_ = std::make_unique<ImageChunk>(CHUNK_NORMAL, 0, &file_content_, zipfile_size);
759 }
760 if (!InitializeChunks(filename, handle)) {
761 CloseArchive(handle);
762 return false;
763 }
764
765 CloseArchive(handle);
766 return true;
767}
768
769// Iterate the zip entries and compose the image chunks accordingly.
770bool ZipModeImage::InitializeChunks(const std::string& filename, ZipArchiveHandle handle) {
771 void* cookie;
772 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
773 if (ret != 0) {
774 printf("failed to iterate over entries in %s: %s\n", filename.c_str(), ErrorCodeString(ret));
775 return false;
776 }
777
778 // Create a list of deflated zip entries, sorted by offset.
779 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
780 ZipString name;
781 ZipEntry entry;
782 while ((ret = Next(cookie, &entry, &name)) == 0) {
783 if (entry.method == kCompressDeflated) {
784 std::string entry_name(name.name, name.name + name.name_length);
785 temp_entries.emplace_back(entry_name, entry);
786 }
787 }
788
789 if (ret != -1) {
790 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
791 return false;
792 }
793 std::sort(temp_entries.begin(), temp_entries.end(),
794 [](auto& entry1, auto& entry2) { return entry1.second.offset < entry2.second.offset; });
795
796 EndIteration(cookie);
797
798 // For source chunks, we don't need to compose chunks for the metadata.
799 if (is_source_) {
800 for (auto& entry : temp_entries) {
801 if (!AddZipEntryToChunks(handle, entry.first, &entry.second)) {
802 printf("Failed to add %s to source chunks\n", entry.first.c_str());
803 return false;
804 }
805 }
806 return true;
807 }
808
809 // For target chunks, add the deflate entries as CHUNK_DEFLATE and the contents between two
810 // deflate entries as CHUNK_NORMAL.
811 size_t pos = 0;
812 size_t nextentry = 0;
813 while (pos < file_content_.size()) {
814 if (nextentry < temp_entries.size() &&
815 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
816 // Add the next zip entry.
817 std::string entry_name = temp_entries[nextentry].first;
818 if (!AddZipEntryToChunks(handle, entry_name, &temp_entries[nextentry].second)) {
819 printf("Failed to add %s to target chunks\n", entry_name.c_str());
820 return false;
821 }
822
823 pos += temp_entries[nextentry].second.compressed_length;
824 ++nextentry;
825 continue;
826 }
827
828 // Use a normal chunk to take all the data up to the start of the next entry.
829 size_t raw_data_len;
830 if (nextentry < temp_entries.size()) {
831 raw_data_len = temp_entries[nextentry].second.offset - pos;
832 } else {
833 raw_data_len = file_content_.size() - pos;
834 }
835 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, raw_data_len);
836
837 pos += raw_data_len;
838 }
839
840 return true;
841}
842
843bool ZipModeImage::AddZipEntryToChunks(ZipArchiveHandle handle, const std::string& entry_name,
844 ZipEntry* entry) {
845 size_t compressed_len = entry->compressed_length;
846 if (entry->method == kCompressDeflated) {
847 size_t uncompressed_len = entry->uncompressed_length;
848 std::vector<uint8_t> uncompressed_data(uncompressed_len);
849 int ret = ExtractToMemory(handle, entry, uncompressed_data.data(), uncompressed_len);
850 if (ret != 0) {
851 printf("failed to extract %s with size %zu: %s\n", entry_name.c_str(), uncompressed_len,
852 ErrorCodeString(ret));
853 return false;
854 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700855 ImageChunk curr(CHUNK_DEFLATE, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700856 curr.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700857 chunks_.push_back(std::move(curr));
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700858 } else {
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700859 chunks_.emplace_back(CHUNK_NORMAL, entry->offset, &file_content_, compressed_len, entry_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700860 }
861
862 return true;
863}
864
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800865// EOCD record
866// offset 0: signature 0x06054b50, 4 bytes
867// offset 4: number of this disk, 2 bytes
868// ...
869// offset 20: comment length, 2 bytes
870// offset 22: comment, n bytes
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700871bool ZipModeImage::GetZipFileSize(size_t* input_file_size) {
872 if (file_content_.size() < 22) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800873 printf("file is too small to be a zip file\n");
874 return false;
875 }
876
877 // Look for End of central directory record of the zip file, and calculate the actual
878 // zip_file size.
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700879 for (int i = file_content_.size() - 22; i >= 0; i--) {
880 if (file_content_[i] == 0x50) {
881 if (get_unaligned<uint32_t>(&file_content_[i]) == 0x06054b50) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800882 // double-check: this archive consists of a single "disk".
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700883 CHECK_EQ(get_unaligned<uint16_t>(&file_content_[i + 4]), 0);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800884
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700885 uint16_t comment_length = get_unaligned<uint16_t>(&file_content_[i + 20]);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800886 size_t file_size = i + 22 + comment_length;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700887 CHECK_LE(file_size, file_content_.size());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800888 *input_file_size = file_size;
889 return true;
890 }
891 }
892 }
893
894 // EOCD not found, this file is likely not a valid zip file.
895 return false;
896}
897
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700898bool ZipModeImage::CheckAndProcessChunks(ZipModeImage* tgt_image, ZipModeImage* src_image) {
899 for (auto& tgt_chunk : *tgt_image) {
900 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800901 continue;
902 }
903
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700904 ImageChunk* src_chunk = src_image->FindChunkByName(tgt_chunk.GetEntryName());
905 if (src_chunk == nullptr) {
906 tgt_chunk.ChangeDeflateChunkToNormal();
907 } else if (tgt_chunk == *src_chunk) {
908 // If two deflate chunks are identical (eg, the kernel has not changed between two builds),
909 // treat them as normal chunks. This makes applypatch much faster -- it can apply a trivial
910 // patch to the compressed data, rather than uncompressing and recompressing to apply the
911 // trivial patch to the uncompressed data.
912 tgt_chunk.ChangeDeflateChunkToNormal();
913 src_chunk->ChangeDeflateChunkToNormal();
914 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
915 // We cannot recompress the data and get exactly the same bits as are in the input target
916 // image. Treat the chunk as a normal non-deflated chunk.
917 printf("failed to reconstruct target deflate chunk [%s]; treating as normal\n",
918 tgt_chunk.GetEntryName().c_str());
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800919
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700920 tgt_chunk.ChangeDeflateChunkToNormal();
921 src_chunk->ChangeDeflateChunkToNormal();
922 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800923 }
924
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700925 // For zips, we only need merge normal chunks for the target: deflated chunks are matched via
926 // filename, and normal chunks are patched using the entire source file as the source.
927 tgt_image->MergeAdjacentNormalChunks();
928 tgt_image->DumpChunks();
Tianjie Xu12b90552017-03-07 14:44:14 -0800929
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700930 return true;
931}
932
933bool ZipModeImage::GeneratePatches(const ZipModeImage& tgt_image, const ZipModeImage& src_image,
934 const std::string& patch_name) {
935 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
936 std::vector<PatchChunk> patch_chunks;
937 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700938
939 saidx_t* bsdiff_cache = nullptr;
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700940 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
941 const auto& tgt_chunk = tgt_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700942
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700943 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
944 patch_chunks.emplace_back(tgt_chunk);
945 continue;
946 }
947
948 const ImageChunk* src_chunk = (tgt_chunk.GetType() != CHUNK_DEFLATE)
949 ? nullptr
950 : src_image.FindChunkByName(tgt_chunk.GetEntryName());
951
952 const auto& src_ref = (src_chunk == nullptr) ? src_image.PseudoSource() : *src_chunk;
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700953 saidx_t** bsdiff_cache_ptr = (src_chunk == nullptr) ? &bsdiff_cache : nullptr;
954
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700955 std::vector<uint8_t> patch_data;
956 if (!ImageChunk::MakePatch(tgt_chunk, src_ref, &patch_data, bsdiff_cache_ptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700957 printf("Failed to generate patch, name: %s\n", tgt_chunk.GetEntryName().c_str());
958 return false;
959 }
960
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700961 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700962 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700963
964 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
965 patch_chunks.emplace_back(tgt_chunk);
966 } else {
967 patch_chunks.emplace_back(tgt_chunk, src_ref, std::move(patch_data));
968 }
Tianjie Xu12b90552017-03-07 14:44:14 -0800969 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700970 free(bsdiff_cache);
971
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700972 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
973
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700974 android::base::unique_fd patch_fd(
975 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
976 if (patch_fd == -1) {
977 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800978 return false;
979 }
980
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700981 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700982}
983
984class ImageModeImage : public Image {
985 public:
986 explicit ImageModeImage(bool is_source) : Image(is_source) {}
987
988 // Initialize the image chunks list by searching the magic numbers in an image file.
989 bool Initialize(const std::string& filename) override;
990
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700991 bool SetBonusData(const std::vector<uint8_t>& bonus_data);
992
Tianjie Xu6b03ba72017-07-19 14:16:30 -0700993 // In Image Mode, verify that the source and target images have the same chunk structure (ie, the
994 // same sequence of deflate and normal chunks).
995 static bool CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image);
996
997 // In image mode, generate patches against the given source chunks and bonus_data; write the
998 // result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -0700999 static bool GeneratePatches(const ImageModeImage& tgt_image, const ImageModeImage& src_image,
1000 const std::string& patch_name);
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001001};
1002
1003bool ImageModeImage::Initialize(const std::string& filename) {
1004 if (!ReadFile(filename, &file_content_)) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001005 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001006 }
Doug Zongker512536a2010-02-17 16:11:44 -08001007
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001008 size_t sz = file_content_.size();
Doug Zongker512536a2010-02-17 16:11:44 -08001009 size_t pos = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -07001010 while (pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001011 // 0x00 no header flags, 0x08 deflate compression, 0x1f8b gzip magic number
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001012 if (sz - pos >= 4 && get_unaligned<uint32_t>(file_content_.data() + pos) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001013 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +02001014 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001015
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001016 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
1017 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001018 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, sz - pos);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001019 break;
1020 }
Doug Zongker512536a2010-02-17 16:11:44 -08001021
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001022 // We need three chunks for the deflated image in total, one normal chunk for the header,
1023 // one deflated chunk for the body, and another normal chunk for the footer.
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001024 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_HEADER_LEN);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001025 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001026
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001027 // We must decompress this chunk in order to discover where it ends, and so we can update
1028 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -08001029
1030 z_stream strm;
1031 strm.zalloc = Z_NULL;
1032 strm.zfree = Z_NULL;
1033 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -07001034 strm.avail_in = sz - pos;
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001035 strm.next_in = file_content_.data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001036
1037 // -15 means we are decoding a 'raw' deflate stream; zlib will
1038 // not expect zlib headers.
1039 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001040 if (ret < 0) {
1041 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001042 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -08001043 }
Doug Zongker512536a2010-02-17 16:11:44 -08001044
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001045 size_t allocated = BUFFER_SIZE;
1046 std::vector<uint8_t> uncompressed_data(allocated);
1047 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001048 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001049 strm.avail_out = allocated - uncompressed_len;
1050 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001051 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +02001052 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001053 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -08001054 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001055 break;
Johan Redestigc68bd342015-04-14 21:20:06 +02001056 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001057 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -08001058 if (strm.avail_out == 0) {
1059 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001060 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -08001061 }
1062 } while (ret != Z_STREAM_END);
1063
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001064 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -08001065 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001066
1067 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -08001068 continue;
1069 }
1070
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001071 // The footer contains the size of the uncompressed data. Double-check to make sure that it
1072 // matches the size of the data we got when we actually did the decompression.
1073 size_t footer_index = pos + raw_data_len + GZIP_FOOTER_LEN - 4;
1074 if (sz - footer_index < 4) {
1075 printf("Warning: invalid footer position; treating as a nomal chunk\n");
1076 continue;
1077 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001078 size_t footer_size = get_unaligned<uint32_t>(file_content_.data() + footer_index);
Tianjie Xu14ebc1e2017-07-05 12:04:07 -07001079 if (footer_size != uncompressed_len) {
1080 printf("Warning: footer size %zu != decompressed size %zu; treating as a nomal chunk\n",
1081 footer_size, uncompressed_len);
1082 continue;
1083 }
1084
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001085 ImageChunk body(CHUNK_DEFLATE, pos, &file_content_, raw_data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001086 uncompressed_data.resize(uncompressed_len);
1087 body.SetUncompressedData(std::move(uncompressed_data));
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001088 chunks_.push_back(std::move(body));
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001089
1090 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001091
1092 // create a normal chunk for the footer
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001093 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -08001094
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001095 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -08001096 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001097 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
1098 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -08001099
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001100 // Scan forward until we find a gzip header.
1101 size_t data_len = 0;
1102 while (data_len + pos < sz) {
Tianjie Xu12b90552017-03-07 14:44:14 -08001103 if (data_len + pos + 4 <= sz &&
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001104 get_unaligned<uint32_t>(file_content_.data() + pos + data_len) == 0x00088b1f) {
Doug Zongker512536a2010-02-17 16:11:44 -08001105 break;
1106 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001107 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -08001108 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001109 chunks_.emplace_back(CHUNK_NORMAL, pos, &file_content_, data_len);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001110
1111 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -08001112 }
1113 }
1114
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001115 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001116}
1117
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001118bool ImageModeImage::SetBonusData(const std::vector<uint8_t>& bonus_data) {
1119 CHECK(is_source_);
1120 if (chunks_.size() < 2 || !chunks_[1].SetBonusData(bonus_data)) {
1121 printf("Failed to set bonus data\n");
1122 DumpChunks();
1123 return false;
1124 }
1125
1126 printf(" using %zu bytes of bonus data\n", bonus_data.size());
1127 return true;
1128}
1129
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001130// In Image Mode, verify that the source and target images have the same chunk structure (ie, the
1131// same sequence of deflate and normal chunks).
1132bool ImageModeImage::CheckAndProcessChunks(ImageModeImage* tgt_image, ImageModeImage* src_image) {
1133 // In image mode, merge the gzip header and footer in with any adjacent normal chunks.
1134 tgt_image->MergeAdjacentNormalChunks();
1135 src_image->MergeAdjacentNormalChunks();
Doug Zongker512536a2010-02-17 16:11:44 -08001136
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001137 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1138 printf("source and target don't have same number of chunks!\n");
1139 tgt_image->DumpChunks();
1140 src_image->DumpChunks();
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001141 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +02001142 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001143 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001144 if ((*tgt_image)[i].GetType() != (*src_image)[i].GetType()) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001145 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
1146 tgt_image->DumpChunks();
1147 src_image->DumpChunks();
1148 return false;
1149 }
Doug Zongker512536a2010-02-17 16:11:44 -08001150 }
1151
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001152 for (size_t i = 0; i < tgt_image->NumOfChunks(); ++i) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001153 auto& tgt_chunk = (*tgt_image)[i];
1154 auto& src_chunk = (*src_image)[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001155 if (tgt_chunk.GetType() != CHUNK_DEFLATE) {
1156 continue;
1157 }
1158
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001159 // If two deflate chunks are identical treat them as normal chunks.
1160 if (tgt_chunk == src_chunk) {
1161 tgt_chunk.ChangeDeflateChunkToNormal();
1162 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001163 } else if (!tgt_chunk.ReconstructDeflateChunk()) {
1164 // We cannot recompress the data and get exactly the same bits as are in the input target
1165 // image, fall back to normal
1166 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
1167 tgt_chunk.GetEntryName().c_str());
1168 tgt_chunk.ChangeDeflateChunkToNormal();
1169 src_chunk.ChangeDeflateChunkToNormal();
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001170 }
Doug Zongker512536a2010-02-17 16:11:44 -08001171 }
1172
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001173 // For images, we need to maintain the parallel structure of the chunk lists, so do the merging
1174 // in both the source and target lists.
1175 tgt_image->MergeAdjacentNormalChunks();
1176 src_image->MergeAdjacentNormalChunks();
1177 if (tgt_image->NumOfChunks() != src_image->NumOfChunks()) {
1178 // This shouldn't happen.
1179 printf("merging normal chunks went awry\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001180 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001181 }
Doug Zongker512536a2010-02-17 16:11:44 -08001182
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001183 return true;
Doug Zongker512536a2010-02-17 16:11:44 -08001184}
1185
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001186// In image mode, generate patches against the given source chunks and bonus_data; write the
1187// result to |patch_name|.
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001188bool ImageModeImage::GeneratePatches(const ImageModeImage& tgt_image,
1189 const ImageModeImage& src_image,
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001190 const std::string& patch_name) {
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001191 printf("Construct patches for %zu chunks...\n", tgt_image.NumOfChunks());
1192 std::vector<PatchChunk> patch_chunks;
1193 patch_chunks.reserve(tgt_image.NumOfChunks());
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001194
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001195 for (size_t i = 0; i < tgt_image.NumOfChunks(); i++) {
1196 const auto& tgt_chunk = tgt_image[i];
1197 const auto& src_chunk = src_image[i];
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001198
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001199 if (PatchChunk::RawDataIsSmaller(tgt_chunk, 0)) {
1200 patch_chunks.emplace_back(tgt_chunk);
1201 continue;
Doug Zongker512536a2010-02-17 16:11:44 -08001202 }
1203
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001204 std::vector<uint8_t> patch_data;
1205 if (!ImageChunk::MakePatch(tgt_chunk, src_chunk, &patch_data, nullptr)) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001206 printf("Failed to generate patch for target chunk %zu: ", i);
1207 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001208 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001209 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data.size(),
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001210 tgt_chunk.GetRawDataLength());
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001211
1212 if (PatchChunk::RawDataIsSmaller(tgt_chunk, patch_data.size())) {
1213 patch_chunks.emplace_back(tgt_chunk);
1214 } else {
1215 patch_chunks.emplace_back(tgt_chunk, src_chunk, std::move(patch_data));
1216 }
Doug Zongker512536a2010-02-17 16:11:44 -08001217 }
Doug Zongker512536a2010-02-17 16:11:44 -08001218
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001219 CHECK_EQ(tgt_image.NumOfChunks(), patch_chunks.size());
1220
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001221 android::base::unique_fd patch_fd(
1222 open(patch_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR));
1223 if (patch_fd == -1) {
1224 printf("failed to open \"%s\": %s\n", patch_name.c_str(), strerror(errno));
1225 return false;
Doug Zongker512536a2010-02-17 16:11:44 -08001226 }
Doug Zongker512536a2010-02-17 16:11:44 -08001227
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001228 return PatchChunk::WritePatchDataToFd(patch_chunks, patch_fd);
Doug Zongker512536a2010-02-17 16:11:44 -08001229}
1230
Tao Bao97555da2016-12-15 10:15:06 -08001231int imgdiff(int argc, const char** argv) {
1232 bool zip_mode = false;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001233 std::vector<uint8_t> bonus_data;
Tianjie Xu12b90552017-03-07 14:44:14 -08001234
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001235 int opt;
1236 optind = 1; // Reset the getopt state so that we can call it multiple times for test.
Doug Zongkera3ccba62012-08-20 15:28:02 -07001237
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001238 while ((opt = getopt(argc, const_cast<char**>(argv), "zb:")) != -1) {
1239 switch (opt) {
1240 case 'z':
1241 zip_mode = true;
1242 break;
1243 case 'b': {
1244 android::base::unique_fd fd(open(optarg, O_RDONLY));
1245 if (fd == -1) {
1246 printf("failed to open bonus file %s: %s\n", optarg, strerror(errno));
1247 return 1;
1248 }
1249 struct stat st;
1250 if (fstat(fd, &st) != 0) {
1251 printf("failed to stat bonus file %s: %s\n", optarg, strerror(errno));
1252 return 1;
1253 }
1254
1255 size_t bonus_size = st.st_size;
1256 bonus_data.resize(bonus_size);
1257 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
1258 printf("failed to read bonus file %s: %s\n", optarg, strerror(errno));
1259 return 1;
1260 }
1261 break;
1262 }
1263 default:
1264 printf("unexpected opt: %s\n", optarg);
1265 return 2;
1266 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001267 }
1268
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001269 if (argc - optind != 3) {
1270 printf("usage: %s [-z] [-b <bonus-file>] <src-img> <tgt-img> <patch-file>\n", argv[0]);
Doug Zongkera3ccba62012-08-20 15:28:02 -07001271 return 2;
1272 }
Doug Zongker512536a2010-02-17 16:11:44 -08001273
Doug Zongker512536a2010-02-17 16:11:44 -08001274 if (zip_mode) {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001275 ZipModeImage src_image(true);
1276 ZipModeImage tgt_image(false);
1277
1278 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001279 return 1;
1280 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001281 if (!tgt_image.Initialize(argv[optind + 1])) {
1282 return 1;
1283 }
1284
1285 if (!ZipModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
1286 return 1;
1287 }
1288 // Compute bsdiff patches for each chunk's data (the uncompressed data, in the case of
1289 // deflate chunks).
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001290 if (!ZipModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001291 return 1;
1292 }
1293 } else {
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001294 ImageModeImage src_image(true);
1295 ImageModeImage tgt_image(false);
1296
1297 if (!src_image.Initialize(argv[optind])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001298 return 1;
1299 }
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001300 if (!tgt_image.Initialize(argv[optind + 1])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001301 return 1;
1302 }
1303
Tianjie Xu6b03ba72017-07-19 14:16:30 -07001304 if (!ImageModeImage::CheckAndProcessChunks(&tgt_image, &src_image)) {
Doug Zongker512536a2010-02-17 16:11:44 -08001305 return 1;
1306 }
Tianjie Xud82a2ed2017-08-08 17:35:01 -07001307
1308 if (!bonus_data.empty() && !src_image.SetBonusData(bonus_data)) {
1309 return 1;
1310 }
1311
1312 if (!ImageModeImage::GeneratePatches(tgt_image, src_image, argv[optind + 2])) {
Doug Zongker512536a2010-02-17 16:11:44 -08001313 return 1;
1314 }
1315 }
1316
Doug Zongker512536a2010-02-17 16:11:44 -08001317 return 0;
1318}