blob: fba74e836ea63c9e0fd6994150b6ebe0ada223d5 [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
Doug Zongker512536a2010-02-17 16:11:44 -0800148#include "utils.h"
149
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800150using android::base::get_unaligned;
Doug Zongker512536a2010-02-17 16:11:44 -0800151
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800152static constexpr auto BUFFER_SIZE = 0x8000;
Doug Zongker512536a2010-02-17 16:11:44 -0800153
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800154class ImageChunk {
155 public:
156 static constexpr auto WINDOWBITS = -15; // 32kb window; negative to indicate a raw stream.
157 static constexpr auto MEMLEVEL = 8; // the default value.
158 static constexpr auto METHOD = Z_DEFLATED;
159 static constexpr auto STRATEGY = Z_DEFAULT_STRATEGY;
160
161 ImageChunk(int type, size_t start, const std::vector<uint8_t>* file_content, size_t raw_data_len)
162 : type_(type),
163 start_(start),
164 input_file_ptr_(file_content),
165 raw_data_len_(raw_data_len),
166 entry_name_(""),
167 compress_level_(6),
168 source_start_(0),
169 source_len_(0),
170 source_uncompressed_len_(0) {}
171
172 int GetType() const {
173 return type_;
174 }
175 size_t GetRawDataLength() const {
176 return raw_data_len_;
177 }
178 const std::string& GetEntryName() const {
179 return entry_name_;
180 }
181
182 // CHUNK_DEFLATE will return the uncompressed data for diff, while other types will simply return
183 // the raw data.
184 const uint8_t * DataForPatch() const;
185 size_t DataLengthForPatch() const;
186
187 void Dump() const {
188 printf("type %d start %zu len %zu\n", type_, start_, DataLengthForPatch());
189 }
190
191 void SetSourceInfo(const ImageChunk& other);
192 void SetEntryName(std::string entryname);
193 void SetUncompressedData(std::vector<uint8_t> data);
194 bool SetBonusData(const std::vector<uint8_t>& bonus_data);
195
196 bool operator==(const ImageChunk& other) const;
197 bool operator!=(const ImageChunk& other) const {
198 return !(*this == other);
199 }
200
201 size_t GetHeaderSize(size_t patch_size) const;
202 size_t WriteHeaderToFile(FILE* f, const std::vector<uint8_t> patch, size_t offset);
203
204 /*
205 * Cause a gzip chunk to be treated as a normal chunk (ie, as a blob
206 * of uninterpreted data). The resulting patch will likely be about
207 * as big as the target file, but it lets us handle the case of images
208 * where some gzip chunks are reconstructible but others aren't (by
209 * treating the ones that aren't as normal chunks).
210 */
211 void ChangeDeflateChunkToNormal();
212 bool ChangeChunkToRaw(size_t patch_size);
213
214 /*
215 * Verify that we can reproduce exactly the same compressed data that
216 * we started with. Sets the level, method, windowBits, memLevel, and
217 * strategy fields in the chunk to the encoding parameters needed to
218 * produce the right output.
219 */
220 bool ReconstructDeflateChunk();
221 bool IsAdjacentNormal(const ImageChunk& other) const;
222 void MergeAdjacentNormal(const ImageChunk& other);
223
224 private:
225 int type_; // CHUNK_NORMAL, CHUNK_DEFLATE, CHUNK_RAW
226 size_t start_; // offset of chunk in the original input file
227 const std::vector<uint8_t>* input_file_ptr_; // pointer to the full content of original input file
228 size_t raw_data_len_;
Doug Zongker512536a2010-02-17 16:11:44 -0800229
Doug Zongker512536a2010-02-17 16:11:44 -0800230 // --- for CHUNK_DEFLATE chunks only: ---
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800231 std::vector<uint8_t> uncompressed_data_;
232 std::string entry_name_; // used for zip entries
Doug Zongker512536a2010-02-17 16:11:44 -0800233
234 // deflate encoder parameters
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800235 int compress_level_;
Doug Zongker512536a2010-02-17 16:11:44 -0800236
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800237 size_t source_start_;
238 size_t source_len_;
239 size_t source_uncompressed_len_;
Doug Zongker512536a2010-02-17 16:11:44 -0800240
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800241 const uint8_t* GetRawData() const;
242 bool TryReconstruction(int level);
243};
Doug Zongker512536a2010-02-17 16:11:44 -0800244
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800245const uint8_t* ImageChunk::GetRawData() const {
246 CHECK_LE(start_ + raw_data_len_, input_file_ptr_->size());
247 return input_file_ptr_->data() + start_;
248}
249
250const uint8_t * ImageChunk::DataForPatch() const {
251 if (type_ == CHUNK_DEFLATE) {
252 return uncompressed_data_.data();
253 }
254 return GetRawData();
255}
256
257size_t ImageChunk::DataLengthForPatch() const {
258 if (type_ == CHUNK_DEFLATE) {
259 return uncompressed_data_.size();
260 }
261 return raw_data_len_;
262}
263
264bool ImageChunk::operator==(const ImageChunk& other) const {
265 if (type_ != other.type_) {
266 return false;
267 }
268 return (raw_data_len_ == other.raw_data_len_ &&
269 memcmp(GetRawData(), other.GetRawData(), raw_data_len_) == 0);
270}
271
272void ImageChunk::SetSourceInfo(const ImageChunk& src) {
273 source_start_ = src.start_;
274 if (type_ == CHUNK_NORMAL) {
275 source_len_ = src.raw_data_len_;
276 } else if (type_ == CHUNK_DEFLATE) {
277 source_len_ = src.raw_data_len_;
278 source_uncompressed_len_ = src.uncompressed_data_.size();
Tao Baoa0c40112016-06-01 13:15:44 -0700279 }
Doug Zongker512536a2010-02-17 16:11:44 -0800280}
281
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800282void ImageChunk::SetEntryName(std::string entryname) {
283 entry_name_ = entryname;
284}
285
286void ImageChunk::SetUncompressedData(std::vector<uint8_t> data) {
287 uncompressed_data_ = data;
288}
289
290bool ImageChunk::SetBonusData(const std::vector<uint8_t>& bonus_data) {
291 if (type_ != CHUNK_DEFLATE) {
292 return false;
293 }
294 uncompressed_data_.insert(uncompressed_data_.end(), bonus_data.begin(), bonus_data.end());
295 return true;
296}
297
298// Convert CHUNK_NORMAL & CHUNK_DEFLATE to CHUNK_RAW if the terget size is
299// smaller. Also take the header size into account during size comparison.
300bool ImageChunk::ChangeChunkToRaw(size_t patch_size) {
301 if (type_ == CHUNK_RAW) {
302 return true;
303 } else if (type_ == CHUNK_NORMAL && (raw_data_len_ <= 160 || raw_data_len_ < patch_size)) {
304 type_ = CHUNK_RAW;
305 return true;
306 }
307 return false;
308}
309
310void ImageChunk::ChangeDeflateChunkToNormal() {
311 if (type_ != CHUNK_DEFLATE) return;
312 type_ = CHUNK_NORMAL;
313 uncompressed_data_.clear();
314}
315
316// Header size:
317// header_type 4 bytes
318// CHUNK_NORMAL 8*3 = 24 bytes
319// CHUNK_DEFLATE 8*5 + 4*5 = 60 bytes
320// CHUNK_RAW 4 bytes
321size_t ImageChunk::GetHeaderSize(size_t patch_size) const {
322 switch (type_) {
323 case CHUNK_NORMAL:
324 return 4 + 8 * 3;
325 case CHUNK_DEFLATE:
326 return 4 + 8 * 5 + 4 * 5;
327 case CHUNK_RAW:
328 return 4 + 4 + patch_size;
329 default:
330 printf("unexpected chunk type: %d\n", type_); // should not reach here.
331 CHECK(false);
332 return 0;
333 }
334}
335
336size_t ImageChunk::WriteHeaderToFile(FILE* f, const std::vector<uint8_t> patch, size_t offset) {
337 Write4(type_, f);
338 switch (type_) {
339 case CHUNK_NORMAL:
340 printf("normal (%10zu, %10zu) %10zu\n", start_, raw_data_len_, patch.size());
341 Write8(source_start_, f);
342 Write8(source_len_, f);
343 Write8(offset, f);
344 return offset + patch.size();
345 case CHUNK_DEFLATE:
346 printf("deflate (%10zu, %10zu) %10zu %s\n", start_, raw_data_len_, patch.size(),
347 entry_name_.c_str());
348 Write8(source_start_, f);
349 Write8(source_len_, f);
350 Write8(offset, f);
351 Write8(source_uncompressed_len_, f);
352 Write8(uncompressed_data_.size(), f);
353 Write4(compress_level_, f);
354 Write4(METHOD, f);
355 Write4(WINDOWBITS, f);
356 Write4(MEMLEVEL, f);
357 Write4(STRATEGY, f);
358 return offset + patch.size();
359 case CHUNK_RAW:
360 printf("raw (%10zu, %10zu)\n", start_, raw_data_len_);
361 Write4(patch.size(), f);
362 fwrite(patch.data(), 1, patch.size(), f);
363 return offset;
364 default:
365 printf("unexpected chunk type: %d\n", type_);
366 CHECK(false);
367 return offset;
368 }
369}
370
371bool ImageChunk::IsAdjacentNormal(const ImageChunk& other) const {
372 if (type_ != CHUNK_NORMAL || other.type_ != CHUNK_NORMAL) {
373 return false;
374 }
375 return (other.start_ == start_ + raw_data_len_);
376}
377
378void ImageChunk::MergeAdjacentNormal(const ImageChunk& other) {
379 CHECK(IsAdjacentNormal(other));
380 raw_data_len_ = raw_data_len_ + other.raw_data_len_;
381}
382
383bool ImageChunk::ReconstructDeflateChunk() {
384 if (type_ != CHUNK_DEFLATE) {
385 printf("attempt to reconstruct non-deflate chunk\n");
386 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800387 }
388
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800389 // We only check two combinations of encoder parameters: level 6
390 // (the default) and level 9 (the maximum).
391 for (int level = 6; level <= 9; level += 3) {
392 if (TryReconstruction(level)) {
393 compress_level_ = level;
394 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800395 }
396 }
Doug Zongker512536a2010-02-17 16:11:44 -0800397
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800398 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800399}
400
401/*
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800402 * Takes the uncompressed data stored in the chunk, compresses it
403 * using the zlib parameters stored in the chunk, and checks that it
404 * matches exactly the compressed data we started with (also stored in
405 * the chunk).
Doug Zongker512536a2010-02-17 16:11:44 -0800406 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800407bool ImageChunk::TryReconstruction(int level) {
408 z_stream strm;
409 strm.zalloc = Z_NULL;
410 strm.zfree = Z_NULL;
411 strm.opaque = Z_NULL;
412 strm.avail_in = uncompressed_data_.size();
413 strm.next_in = uncompressed_data_.data();
414 int ret = deflateInit2(&strm, level, METHOD, WINDOWBITS, MEMLEVEL, STRATEGY);
415 if (ret < 0) {
416 printf("failed to initialize deflate: %d\n", ret);
417 return false;
418 }
419
420 std::vector<uint8_t> buffer(BUFFER_SIZE);
421 size_t offset = 0;
422 do {
423 strm.avail_out = buffer.size();
424 strm.next_out = buffer.data();
425 ret = deflate(&strm, Z_FINISH);
426 if (ret < 0) {
427 printf("failed to deflate: %d\n", ret);
428 return false;
429 }
430
431 size_t compressed_size = buffer.size() - strm.avail_out;
432 if (memcmp(buffer.data(), input_file_ptr_->data() + start_ + offset, compressed_size) != 0) {
433 // mismatch; data isn't the same.
434 deflateEnd(&strm);
435 return false;
436 }
437 offset += compressed_size;
438 } while (ret != Z_STREAM_END);
439 deflateEnd(&strm);
440
441 if (offset != raw_data_len_) {
442 // mismatch; ran out of data before we should have.
443 return false;
444 }
445 return true;
446}
447
448// EOCD record
449// offset 0: signature 0x06054b50, 4 bytes
450// offset 4: number of this disk, 2 bytes
451// ...
452// offset 20: comment length, 2 bytes
453// offset 22: comment, n bytes
454static bool GetZipFileSize(const std::vector<uint8_t>& zip_file, size_t* input_file_size) {
455 if (zip_file.size() < 22) {
456 printf("file is too small to be a zip file\n");
457 return false;
458 }
459
460 // Look for End of central directory record of the zip file, and calculate the actual
461 // zip_file size.
462 for (int i = zip_file.size() - 22; i >= 0; i--) {
463 if (zip_file[i] == 0x50) {
464 if (get_unaligned<uint32_t>(&zip_file[i]) == 0x06054b50) {
465 // double-check: this archive consists of a single "disk".
466 CHECK_EQ(get_unaligned<uint16_t>(&zip_file[i + 4]), 0);
467
468 uint16_t comment_length = get_unaligned<uint16_t>(&zip_file[i + 20]);
469 size_t file_size = i + 22 + comment_length;
470 CHECK_LE(file_size, zip_file.size());
471 *input_file_size = file_size;
472 return true;
473 }
474 }
475 }
476
477 // EOCD not found, this file is likely not a valid zip file.
478 return false;
479}
480
481static bool ReadZip(const char* filename, std::vector<ImageChunk>* chunks,
482 std::vector<uint8_t>* zip_file, bool include_pseudo_chunk) {
483 CHECK(zip_file != nullptr);
Doug Zongker512536a2010-02-17 16:11:44 -0800484 struct stat st;
485 if (stat(filename, &st) != 0) {
486 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800487 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800488 }
489
Tao Baoba9a42a2015-06-23 23:23:33 -0700490 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800491 zip_file->resize(sz);
Tao Baod37ce8f2016-12-17 17:10:04 -0800492 android::base::unique_fd fd(open(filename, O_RDONLY));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800493 if (fd == -1) {
494 printf("failed to open \"%s\" %s\n", filename, strerror(errno));
495 return false;
496 }
497 if (!android::base::ReadFully(fd, zip_file->data(), sz)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800498 printf("failed to read \"%s\" %s\n", filename, strerror(errno));
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800499 return false;
500 }
501 fd.reset();
502
503 // Trim the trailing zeros before we pass the file to ziparchive handler.
504 size_t zipfile_size;
505 if (!GetZipFileSize(*zip_file, &zipfile_size)) {
506 printf("failed to parse the actual size of %s\n", filename);
507 return false;
508 }
509 ZipArchiveHandle handle;
510 int err = OpenArchiveFromMemory(zip_file->data(), zipfile_size, filename, &handle);
511 if (err != 0) {
512 printf("failed to open zip file %s: %s\n", filename, ErrorCodeString(err));
513 CloseArchive(handle);
514 return false;
515 }
516
517 // Create a list of deflated zip entries, sorted by offset.
518 std::vector<std::pair<std::string, ZipEntry>> temp_entries;
519 void* cookie;
520 int ret = StartIteration(handle, &cookie, nullptr, nullptr);
521 if (ret != 0) {
522 printf("failed to iterate over entries in %s: %s\n", filename, ErrorCodeString(ret));
523 CloseArchive(handle);
524 return false;
525 }
526
527 ZipString name;
528 ZipEntry entry;
529 while ((ret = Next(cookie, &entry, &name)) == 0) {
530 if (entry.method == kCompressDeflated) {
531 std::string entryname(name.name, name.name + name.name_length);
532 temp_entries.push_back(std::make_pair(entryname, entry));
533 }
534 }
535
536 if (ret != -1) {
537 printf("Error while iterating over zip entries: %s\n", ErrorCodeString(ret));
538 CloseArchive(handle);
539 return false;
540 }
541 std::sort(temp_entries.begin(), temp_entries.end(),
542 [](auto& entry1, auto& entry2) {
543 return entry1.second.offset < entry2.second.offset;
544 });
545
546 EndIteration(cookie);
547
548 if (include_pseudo_chunk) {
549 chunks->emplace_back(CHUNK_NORMAL, 0, zip_file, zip_file->size());
550 }
551
552 size_t pos = 0;
553 size_t nextentry = 0;
554 while (pos < zip_file->size()) {
555 if (nextentry < temp_entries.size() &&
556 static_cast<off64_t>(pos) == temp_entries[nextentry].second.offset) {
557 // compose the next deflate chunk.
558 std::string entryname = temp_entries[nextentry].first;
559 size_t uncompressed_len = temp_entries[nextentry].second.uncompressed_length;
560 std::vector<uint8_t> uncompressed_data(uncompressed_len);
561 if ((ret = ExtractToMemory(handle, &temp_entries[nextentry].second, uncompressed_data.data(),
562 uncompressed_len)) != 0) {
563 printf("failed to extract %s with size %zu: %s\n", entryname.c_str(), uncompressed_len,
564 ErrorCodeString(ret));
565 CloseArchive(handle);
566 return false;
567 }
568
569 size_t compressed_len = temp_entries[nextentry].second.compressed_length;
570 ImageChunk curr(CHUNK_DEFLATE, pos, zip_file, compressed_len);
571 curr.SetEntryName(std::move(entryname));
572 curr.SetUncompressedData(std::move(uncompressed_data));
573 chunks->push_back(curr);
574
575 pos += compressed_len;
576 ++nextentry;
577 continue;
578 }
579
580 // Use a normal chunk to take all the data up to the start of the next deflate section.
581 size_t raw_data_len;
582 if (nextentry < temp_entries.size()) {
583 raw_data_len = temp_entries[nextentry].second.offset - pos;
584 } else {
585 raw_data_len = zip_file->size() - pos;
586 }
587 chunks->emplace_back(CHUNK_NORMAL, pos, zip_file, raw_data_len);
588
589 pos += raw_data_len;
590 }
591
592 CloseArchive(handle);
593 return true;
594}
595
596// Read the given file and break it up into chunks, and putting the data in to a vector.
597static bool ReadImage(const char* filename, std::vector<ImageChunk>* chunks,
598 std::vector<uint8_t>* img) {
599 CHECK(img != nullptr);
600 struct stat st;
601 if (stat(filename, &st) != 0) {
602 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
603 return false;
604 }
605
606 size_t sz = static_cast<size_t>(st.st_size);
607 img->resize(sz);
608 android::base::unique_fd fd(open(filename, O_RDONLY));
609 if (fd == -1) {
610 printf("failed to open \"%s\" %s\n", filename, strerror(errno));
611 return false;
612 }
613 if (!android::base::ReadFully(fd, img->data(), sz)) {
614 printf("failed to read \"%s\" %s\n", filename, strerror(errno));
615 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800616 }
Doug Zongker512536a2010-02-17 16:11:44 -0800617
618 size_t pos = 0;
619
Tao Baoba9a42a2015-06-23 23:23:33 -0700620 while (pos < sz) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800621 if (sz - pos >= 4 && img->at(pos) == 0x1f && img->at(pos + 1) == 0x8b &&
622 img->at(pos + 2) == 0x08 && // deflate compression
623 img->at(pos + 3) == 0x00) { // no header flags
Doug Zongker512536a2010-02-17 16:11:44 -0800624 // 'pos' is the offset of the start of a gzip chunk.
Johan Redestigc68bd342015-04-14 21:20:06 +0200625 size_t chunk_offset = pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800626
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800627 // The remaining data is too small to be a gzip chunk; treat them as a normal chunk.
628 if (sz - pos < GZIP_HEADER_LEN + GZIP_FOOTER_LEN) {
629 chunks->emplace_back(CHUNK_NORMAL, pos, img, sz - pos);
630 break;
631 }
Doug Zongker512536a2010-02-17 16:11:44 -0800632
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800633 // We need three chunks for the deflated image in total, one normal chunk for the header,
634 // one deflated chunk for the body, and another normal chunk for the footer.
635 chunks->emplace_back(CHUNK_NORMAL, pos, img, GZIP_HEADER_LEN);
636 pos += GZIP_HEADER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -0800637
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800638 // We must decompress this chunk in order to discover where it ends, and so we can update
639 // the uncompressed_data of the image body and its length.
Doug Zongker512536a2010-02-17 16:11:44 -0800640
641 z_stream strm;
642 strm.zalloc = Z_NULL;
643 strm.zfree = Z_NULL;
644 strm.opaque = Z_NULL;
Tao Baoba9a42a2015-06-23 23:23:33 -0700645 strm.avail_in = sz - pos;
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800646 strm.next_in = img->data() + pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800647
648 // -15 means we are decoding a 'raw' deflate stream; zlib will
649 // not expect zlib headers.
650 int ret = inflateInit2(&strm, -15);
Rahul Chaudhrya793c582016-11-29 17:10:14 -0800651 if (ret < 0) {
652 printf("failed to initialize inflate: %d\n", ret);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800653 return false;
Rahul Chaudhrya793c582016-11-29 17:10:14 -0800654 }
Doug Zongker512536a2010-02-17 16:11:44 -0800655
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800656 size_t allocated = BUFFER_SIZE;
657 std::vector<uint8_t> uncompressed_data(allocated);
658 size_t uncompressed_len = 0, raw_data_len = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800659 do {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800660 strm.avail_out = allocated - uncompressed_len;
661 strm.next_out = uncompressed_data.data() + uncompressed_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800662 ret = inflate(&strm, Z_NO_FLUSH);
Johan Redestigc68bd342015-04-14 21:20:06 +0200663 if (ret < 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800664 printf("Warning: inflate failed [%s] at offset [%zu], treating as a normal chunk\n",
David Riley0779fc92015-12-10 10:18:25 -0800665 strm.msg, chunk_offset);
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800666 break;
Johan Redestigc68bd342015-04-14 21:20:06 +0200667 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800668 uncompressed_len = allocated - strm.avail_out;
Doug Zongker512536a2010-02-17 16:11:44 -0800669 if (strm.avail_out == 0) {
670 allocated *= 2;
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800671 uncompressed_data.resize(allocated);
Doug Zongker512536a2010-02-17 16:11:44 -0800672 }
673 } while (ret != Z_STREAM_END);
674
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800675 raw_data_len = sz - strm.avail_in - pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800676 inflateEnd(&strm);
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800677
678 if (ret < 0) {
Sen Jiangfa4f1b72016-02-11 16:14:23 -0800679 continue;
680 }
681
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800682 ImageChunk body(CHUNK_DEFLATE, pos, img, raw_data_len);
683 uncompressed_data.resize(uncompressed_len);
684 body.SetUncompressedData(std::move(uncompressed_data));
685 chunks->push_back(body);
686
687 pos += raw_data_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800688
689 // create a normal chunk for the footer
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800690 chunks->emplace_back(CHUNK_NORMAL, pos, img, GZIP_FOOTER_LEN);
Doug Zongker512536a2010-02-17 16:11:44 -0800691
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800692 pos += GZIP_FOOTER_LEN;
Doug Zongker512536a2010-02-17 16:11:44 -0800693
694 // The footer (that we just skipped over) contains the size of
695 // the uncompressed data. Double-check to make sure that it
696 // matches the size of the data we got when we actually did
697 // the decompression.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800698 size_t footer_size = Read4(img->data() + pos - 4);
699 if (footer_size != body.DataLengthForPatch()) {
700 printf("Error: footer size %zu != decompressed size %zu\n", footer_size,
701 body.GetRawDataLength());
702 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800703 }
704 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800705 // Use a normal chunk to take all the contents until the next gzip chunk (or EOF); we expect
706 // the number of chunks to be small (5 for typical boot and recovery images).
Doug Zongker512536a2010-02-17 16:11:44 -0800707
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800708 // Scan forward until we find a gzip header.
709 size_t data_len = 0;
710 while (data_len + pos < sz) {
711 if (data_len + pos + 4 <= sz && img->at(pos + data_len) == 0x1f &&
712 img->at(pos + data_len + 1) == 0x8b && img->at(pos + data_len + 2) == 0x08 &&
713 img->at(pos + data_len + 3) == 0x00) {
Doug Zongker512536a2010-02-17 16:11:44 -0800714 break;
715 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800716 data_len++;
Doug Zongker512536a2010-02-17 16:11:44 -0800717 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800718 chunks->emplace_back(CHUNK_NORMAL, pos, img, data_len);
719
720 pos += data_len;
Doug Zongker512536a2010-02-17 16:11:44 -0800721 }
722 }
723
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800724 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800725}
726
727/*
Sen Jiang930edb62017-01-18 17:26:42 -0800728 * Given source and target chunks, compute a bsdiff patch between them.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800729 * Store the result in the patch_data.
Sen Jiang930edb62017-01-18 17:26:42 -0800730 * |bsdiff_cache| can be used to cache the suffix array if the same |src| chunk
731 * is used repeatedly, pass nullptr if not needed.
Doug Zongker512536a2010-02-17 16:11:44 -0800732 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800733static bool MakePatch(const ImageChunk* src, ImageChunk* tgt, std::vector<uint8_t>* patch_data,
734 saidx_t** bsdiff_cache) {
735 if (tgt->ChangeChunkToRaw(0)) {
736 size_t patch_size = tgt->DataLengthForPatch();
737 patch_data->resize(patch_size);
738 std::copy(tgt->DataForPatch(), tgt->DataForPatch() + patch_size, patch_data->begin());
739 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800740 }
741
Tao Bao97555da2016-12-15 10:15:06 -0800742#if defined(__ANDROID__)
743 char ptemp[] = "/data/local/tmp/imgdiff-patch-XXXXXX";
744#else
Doug Zongker512536a2010-02-17 16:11:44 -0800745 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
Tao Bao97555da2016-12-15 10:15:06 -0800746#endif
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800747
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +0200748 int fd = mkstemp(ptemp);
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +0200749 if (fd == -1) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800750 printf("MakePatch failed to create a temporary file: %s\n", strerror(errno));
751 return false;
Jeremy Compostellaa91c66d2015-09-08 19:15:09 +0200752 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800753 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800754
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800755 int r = bsdiff::bsdiff(src->DataForPatch(), src->DataLengthForPatch(), tgt->DataForPatch(),
756 tgt->DataLengthForPatch(), ptemp, bsdiff_cache);
Doug Zongker512536a2010-02-17 16:11:44 -0800757 if (r != 0) {
758 printf("bsdiff() failed: %d\n", r);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800759 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800760 }
761
762 struct stat st;
763 if (stat(ptemp, &st) != 0) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800764 printf("failed to stat patch file %s: %s\n", ptemp, strerror(errno));
765 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800766 }
767
Tao Baoba9a42a2015-06-23 23:23:33 -0700768 size_t sz = static_cast<size_t>(st.st_size);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800769 if (tgt->ChangeChunkToRaw(sz)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800770 unlink(ptemp);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800771 size_t patch_size = tgt->DataLengthForPatch();
772 patch_data->resize(patch_size);
773 std::copy(tgt->DataForPatch(), tgt->DataForPatch() + patch_size, patch_data->begin());
774 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800775 }
776
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800777 android::base::unique_fd patch_fd(open(ptemp, O_RDONLY));
778 if (patch_fd == -1) {
779 printf("failed to open %s: %s\n", ptemp, strerror(errno));
780 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800781 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800782 patch_data->resize(sz);
783 if (!android::base::ReadFully(patch_fd, patch_data->data(), sz)) {
784 printf("failed to read \"%s\" %s\n", ptemp, strerror(errno));
785 return false;
Doug Zongker512536a2010-02-17 16:11:44 -0800786 }
Doug Zongker512536a2010-02-17 16:11:44 -0800787
788 unlink(ptemp);
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800789 tgt->SetSourceInfo(*src);
Doug Zongker512536a2010-02-17 16:11:44 -0800790
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800791 return true;
Doug Zongker512536a2010-02-17 16:11:44 -0800792}
793
794/*
795 * Look for runs of adjacent normal chunks and compress them down into
796 * a single chunk. (Such runs can be produced when deflate chunks are
797 * changed to normal chunks.)
798 */
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800799static void MergeAdjacentNormalChunks(std::vector<ImageChunk>* chunks) {
800 size_t merged_last = 0, cur = 0;
801 while (cur < chunks->size()) {
802 // Look for normal chunks adjacent to the current one. If such chunk exists, extend the
803 // length of the current normal chunk.
804 size_t to_check = cur + 1;
805 while (to_check < chunks->size() && chunks->at(cur).IsAdjacentNormal(chunks->at(to_check))) {
806 chunks->at(cur).MergeAdjacentNormal(chunks->at(to_check));
807 to_check++;
Doug Zongker512536a2010-02-17 16:11:44 -0800808 }
809
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800810 if (merged_last != cur) {
811 chunks->at(merged_last) = std::move(chunks->at(cur));
Doug Zongker512536a2010-02-17 16:11:44 -0800812 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800813 merged_last++;
814 cur = to_check;
Doug Zongker512536a2010-02-17 16:11:44 -0800815 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800816 if (merged_last < chunks->size()) {
817 chunks->erase(chunks->begin() + merged_last, chunks->end());
818 }
Doug Zongker512536a2010-02-17 16:11:44 -0800819}
820
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800821static ImageChunk* FindChunkByName(const std::string& name, std::vector<ImageChunk>& chunks) {
822 for (size_t i = 0; i < chunks.size(); ++i) {
823 if (chunks[i].GetType() == CHUNK_DEFLATE && chunks[i].GetEntryName() == name) {
824 return &chunks[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800825 }
826 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800827 return nullptr;
Doug Zongker512536a2010-02-17 16:11:44 -0800828}
829
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800830static void DumpChunks(const std::vector<ImageChunk>& chunks) {
831 for (size_t i = 0; i < chunks.size(); ++i) {
832 printf("chunk %zu: ", i);
833 chunks[i].Dump();
834 }
Doug Zongker512536a2010-02-17 16:11:44 -0800835}
836
Tao Bao97555da2016-12-15 10:15:06 -0800837int imgdiff(int argc, const char** argv) {
838 bool zip_mode = false;
Doug Zongker512536a2010-02-17 16:11:44 -0800839
Doug Zongkera3ccba62012-08-20 15:28:02 -0700840 if (argc >= 2 && strcmp(argv[1], "-z") == 0) {
Tao Bao97555da2016-12-15 10:15:06 -0800841 zip_mode = true;
Doug Zongker512536a2010-02-17 16:11:44 -0800842 --argc;
843 ++argv;
844 }
845
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800846 std::vector<uint8_t> bonus_data;
Doug Zongkera3ccba62012-08-20 15:28:02 -0700847 if (argc >= 3 && strcmp(argv[1], "-b") == 0) {
848 struct stat st;
849 if (stat(argv[2], &st) != 0) {
850 printf("failed to stat bonus file %s: %s\n", argv[2], strerror(errno));
851 return 1;
852 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800853 size_t bonus_size = st.st_size;
854 bonus_data.resize(bonus_size);
855 android::base::unique_fd fd(open(argv[2], O_RDONLY));
856 if (fd == -1) {
Doug Zongkera3ccba62012-08-20 15:28:02 -0700857 printf("failed to open bonus file %s: %s\n", argv[2], strerror(errno));
858 return 1;
859 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800860 if (!android::base::ReadFully(fd, bonus_data.data(), bonus_size)) {
Doug Zongkera3ccba62012-08-20 15:28:02 -0700861 printf("failed to read bonus file %s: %s\n", argv[2], strerror(errno));
862 return 1;
863 }
Doug Zongkera3ccba62012-08-20 15:28:02 -0700864
865 argc -= 2;
866 argv += 2;
867 }
868
869 if (argc != 4) {
Doug Zongkera3ccba62012-08-20 15:28:02 -0700870 printf("usage: %s [-z] [-b <bonus-file>] <src-img> <tgt-img> <patch-file>\n",
871 argv[0]);
872 return 2;
873 }
Doug Zongker512536a2010-02-17 16:11:44 -0800874
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800875 std::vector<ImageChunk> src_chunks;
876 std::vector<ImageChunk> tgt_chunks;
877 std::vector<uint8_t> src_file;
878 std::vector<uint8_t> tgt_file;
Doug Zongker512536a2010-02-17 16:11:44 -0800879
880 if (zip_mode) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800881 if (!ReadZip(argv[1], &src_chunks, &src_file, true)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800882 printf("failed to break apart source zip file\n");
883 return 1;
884 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800885 if (!ReadZip(argv[2], &tgt_chunks, &tgt_file, false)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800886 printf("failed to break apart target zip file\n");
887 return 1;
888 }
889 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800890 if (!ReadImage(argv[1], &src_chunks, &src_file)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800891 printf("failed to break apart source image\n");
892 return 1;
893 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800894 if (!ReadImage(argv[2], &tgt_chunks, &tgt_file)) {
Doug Zongker512536a2010-02-17 16:11:44 -0800895 printf("failed to break apart target image\n");
896 return 1;
897 }
898
899 // Verify that the source and target images have the same chunk
900 // structure (ie, the same sequence of deflate and normal chunks).
901
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800902 // Merge the gzip header and footer in with any adjacent normal chunks.
903 MergeAdjacentNormalChunks(&tgt_chunks);
904 MergeAdjacentNormalChunks(&src_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800905
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800906 if (src_chunks.size() != tgt_chunks.size()) {
Doug Zongker512536a2010-02-17 16:11:44 -0800907 printf("source and target don't have same number of chunks!\n");
908 printf("source chunks:\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800909 DumpChunks(src_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800910 printf("target chunks:\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800911 DumpChunks(tgt_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800912 return 1;
913 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800914 for (size_t i = 0; i < src_chunks.size(); ++i) {
915 if (src_chunks[i].GetType() != tgt_chunks[i].GetType()) {
916 printf("source and target don't have same chunk structure! (chunk %zu)\n", i);
Doug Zongker512536a2010-02-17 16:11:44 -0800917 printf("source chunks:\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800918 DumpChunks(src_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800919 printf("target chunks:\n");
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800920 DumpChunks(tgt_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800921 return 1;
922 }
923 }
924 }
925
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800926 for (size_t i = 0; i < tgt_chunks.size(); ++i) {
927 if (tgt_chunks[i].GetType() == CHUNK_DEFLATE) {
Doug Zongker512536a2010-02-17 16:11:44 -0800928 // Confirm that given the uncompressed chunk data in the target, we
929 // can recompress it and get exactly the same bits as are in the
930 // input target image. If this fails, treat the chunk as a normal
931 // non-deflated chunk.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800932 if (!tgt_chunks[i].ReconstructDeflateChunk()) {
933 printf("failed to reconstruct target deflate chunk %zu [%s]; treating as normal\n", i,
934 tgt_chunks[i].GetEntryName().c_str());
935 tgt_chunks[i].ChangeDeflateChunkToNormal();
Doug Zongker512536a2010-02-17 16:11:44 -0800936 if (zip_mode) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800937 ImageChunk* src = FindChunkByName(tgt_chunks[i].GetEntryName(), src_chunks);
938 if (src != nullptr) {
939 src->ChangeDeflateChunkToNormal();
Doug Zongker512536a2010-02-17 16:11:44 -0800940 }
941 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800942 src_chunks[i].ChangeDeflateChunkToNormal();
Doug Zongker512536a2010-02-17 16:11:44 -0800943 }
944 continue;
945 }
946
947 // If two deflate chunks are identical (eg, the kernel has not
948 // changed between two builds), treat them as normal chunks.
949 // This makes applypatch much faster -- it can apply a trivial
950 // patch to the compressed data, rather than uncompressing and
951 // recompressing to apply the trivial patch to the uncompressed
952 // data.
953 ImageChunk* src;
954 if (zip_mode) {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800955 src = FindChunkByName(tgt_chunks[i].GetEntryName(), src_chunks);
Doug Zongker512536a2010-02-17 16:11:44 -0800956 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800957 src = &src_chunks[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800958 }
959
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800960 if (src == nullptr) {
961 tgt_chunks[i].ChangeDeflateChunkToNormal();
962 } else if (tgt_chunks[i] == *src) {
963 tgt_chunks[i].ChangeDeflateChunkToNormal();
964 src->ChangeDeflateChunkToNormal();
Doug Zongker512536a2010-02-17 16:11:44 -0800965 }
966 }
967 }
968
969 // Merging neighboring normal chunks.
970 if (zip_mode) {
971 // For zips, we only need to do this to the target: deflated
972 // chunks are matched via filename, and normal chunks are patched
973 // using the entire source file as the source.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800974 MergeAdjacentNormalChunks(&tgt_chunks);
975
Doug Zongker512536a2010-02-17 16:11:44 -0800976 } else {
977 // For images, we need to maintain the parallel structure of the
978 // chunk lists, so do the merging in both the source and target
979 // lists.
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800980 MergeAdjacentNormalChunks(&tgt_chunks);
981 MergeAdjacentNormalChunks(&src_chunks);
982 if (src_chunks.size() != tgt_chunks.size()) {
Doug Zongker512536a2010-02-17 16:11:44 -0800983 // This shouldn't happen.
984 printf("merging normal chunks went awry\n");
985 return 1;
986 }
987 }
988
989 // Compute bsdiff patches for each chunk's data (the uncompressed
990 // data, in the case of deflate chunks).
991
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800992 DumpChunks(src_chunks);
Doug Zongkera3ccba62012-08-20 15:28:02 -0700993
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800994 printf("Construct patches for %zu chunks...\n", tgt_chunks.size());
995 std::vector<std::vector<uint8_t>> patch_data(tgt_chunks.size());
Sen Jiang930edb62017-01-18 17:26:42 -0800996 saidx_t* bsdiff_cache = nullptr;
Tianjie Xu1ea84d62017-02-22 18:23:58 -0800997 for (size_t i = 0; i < tgt_chunks.size(); ++i) {
Doug Zongker512536a2010-02-17 16:11:44 -0800998 if (zip_mode) {
999 ImageChunk* src;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001000 if (tgt_chunks[i].GetType() == CHUNK_DEFLATE &&
1001 (src = FindChunkByName(tgt_chunks[i].GetEntryName(), src_chunks))) {
1002 MakePatch(src, &tgt_chunks[i], &patch_data[i], nullptr);
Doug Zongker512536a2010-02-17 16:11:44 -08001003 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001004 MakePatch(&src_chunks[0], &tgt_chunks[i], &patch_data[i], &bsdiff_cache);
Doug Zongker512536a2010-02-17 16:11:44 -08001005 }
1006 } else {
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001007 if (i == 1 && !bonus_data.empty()) {
1008 printf(" using %zu bytes of bonus data for chunk %zu\n", bonus_data.size(), i);
1009 src_chunks[i].SetBonusData(bonus_data);
Sen Jiang930edb62017-01-18 17:26:42 -08001010 }
Doug Zongkera3ccba62012-08-20 15:28:02 -07001011
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001012 MakePatch(&src_chunks[i], &tgt_chunks[i], &patch_data[i], nullptr);
Doug Zongker512536a2010-02-17 16:11:44 -08001013 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001014 printf("patch %3zu is %zu bytes (of %zu)\n", i, patch_data[i].size(),
1015 src_chunks[i].GetRawDataLength());
Doug Zongker512536a2010-02-17 16:11:44 -08001016 }
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001017
1018 if (bsdiff_cache != nullptr) {
1019 free(bsdiff_cache);
1020 }
Doug Zongker512536a2010-02-17 16:11:44 -08001021
1022 // Figure out how big the imgdiff file header is going to be, so
1023 // that we can correctly compute the offset of each bsdiff patch
1024 // within the file.
1025
1026 size_t total_header_size = 12;
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001027 for (size_t i = 0; i < tgt_chunks.size(); ++i) {
1028 total_header_size += tgt_chunks[i].GetHeaderSize(patch_data[i].size());
Doug Zongker512536a2010-02-17 16:11:44 -08001029 }
1030
1031 size_t offset = total_header_size;
1032
1033 FILE* f = fopen(argv[3], "wb");
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001034 if (f == nullptr) {
1035 printf("failed to open \"%s\": %s\n", argv[3], strerror(errno));
1036 }
Doug Zongker512536a2010-02-17 16:11:44 -08001037
1038 // Write out the headers.
1039
1040 fwrite("IMGDIFF2", 1, 8, f);
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001041 Write4(static_cast<int32_t>(tgt_chunks.size()), f);
1042 for (size_t i = 0; i < tgt_chunks.size(); ++i) {
1043 printf("chunk %zu: ", i);
1044 offset = tgt_chunks[i].WriteHeaderToFile(f, patch_data[i], offset);
Doug Zongker512536a2010-02-17 16:11:44 -08001045 }
1046
1047 // Append each chunk's bsdiff patch, in order.
Tianjie Xu1ea84d62017-02-22 18:23:58 -08001048 for (size_t i = 0; i < tgt_chunks.size(); ++i) {
1049 if (tgt_chunks[i].GetType() != CHUNK_RAW) {
1050 fwrite(patch_data[i].data(), 1, patch_data[i].size(), f);
Doug Zongker512536a2010-02-17 16:11:44 -08001051 }
1052 }
1053
1054 fclose(f);
Doug Zongker512536a2010-02-17 16:11:44 -08001055
1056 return 0;
1057}