blob: 51835b4050648082ea3e6ffd5b35eb152c6b4b3e [file] [log] [blame]
Doug Zongker02d444b2009-05-27 18:24:03 -07001/*
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:
Doug Zongker6b2bb3d2009-07-20 14:45:29 -070067 * 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]
Doug Zongker02d444b2009-05-27 18:24:03 -070076 * 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)
Doug Zongker6b2bb3d2009-07-20 14:45:29 -070086 * 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)
Doug Zongker02d444b2009-05-27 18:24:03 -0700100 *
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.
114 */
115
116#include <errno.h>
117#include <stdio.h>
118#include <stdlib.h>
119#include <string.h>
120#include <sys/stat.h>
121#include <unistd.h>
122
123#include "zlib.h"
124#include "imgdiff.h"
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700125#include "utils.h"
Doug Zongker02d444b2009-05-27 18:24:03 -0700126
127typedef struct {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700128 int type; // CHUNK_NORMAL, CHUNK_DEFLATE
Doug Zongker02d444b2009-05-27 18:24:03 -0700129 size_t start; // offset of chunk in original image file
130
131 size_t len;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700132 unsigned char* data; // data to be patched (uncompressed, for deflate chunks)
Doug Zongker02d444b2009-05-27 18:24:03 -0700133
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700134 size_t source_start;
135 size_t source_len;
Doug Zongker02d444b2009-05-27 18:24:03 -0700136
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700137 // --- for CHUNK_DEFLATE chunks only: ---
Doug Zongker02d444b2009-05-27 18:24:03 -0700138
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700139 // original (compressed) deflate data
140 size_t deflate_len;
141 unsigned char* deflate_data;
142
143 char* filename; // used for zip entries
Doug Zongker02d444b2009-05-27 18:24:03 -0700144
145 // deflate encoder parameters
146 int level, method, windowBits, memLevel, strategy;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700147
148 size_t source_uncompressed_len;
Doug Zongker02d444b2009-05-27 18:24:03 -0700149} ImageChunk;
150
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700151typedef struct {
152 int data_offset;
153 int deflate_len;
154 int uncomp_len;
155 char* filename;
156} ZipFileEntry;
157
158static int fileentry_compare(const void* a, const void* b) {
159 int ao = ((ZipFileEntry*)a)->data_offset;
160 int bo = ((ZipFileEntry*)b)->data_offset;
161 if (ao < bo) {
162 return -1;
163 } else if (ao > bo) {
164 return 1;
165 } else {
166 return 0;
167 }
168}
169
170unsigned char* ReadZip(const char* filename,
171 int* num_chunks, ImageChunk** chunks,
172 int include_pseudo_chunk) {
173 struct stat st;
174 if (stat(filename, &st) != 0) {
175 fprintf(stderr, "failed to stat \"%s\": %s\n", filename, strerror(errno));
176 return NULL;
177 }
178
179 unsigned char* img = malloc(st.st_size);
180 FILE* f = fopen(filename, "rb");
181 if (fread(img, 1, st.st_size, f) != st.st_size) {
182 fprintf(stderr, "failed to read \"%s\" %s\n", filename, strerror(errno));
183 fclose(f);
184 return NULL;
185 }
186 fclose(f);
187
188 // look for the end-of-central-directory record.
189
190 int i;
191 for (i = st.st_size-20; i >= 0 && i > st.st_size - 65600; --i) {
192 if (img[i] == 0x50 && img[i+1] == 0x4b &&
193 img[i+2] == 0x05 && img[i+3] == 0x06) {
194 break;
195 }
196 }
197 // double-check: this archive consists of a single "disk"
198 if (!(img[i+4] == 0 && img[i+5] == 0 && img[i+6] == 0 && img[i+7] == 0)) {
199 fprintf(stderr, "can't process multi-disk archive\n");
200 return NULL;
201 }
202
203 int cdcount = Read2(img+i+8);
204 int cdoffset = Read4(img+i+16);
205
206 ZipFileEntry* temp_entries = malloc(cdcount * sizeof(ZipFileEntry));
207 int entrycount = 0;
208
209 unsigned char* cd = img+cdoffset;
210 for (i = 0; i < cdcount; ++i) {
211 if (!(cd[0] == 0x50 && cd[1] == 0x4b && cd[2] == 0x01 && cd[3] == 0x02)) {
212 fprintf(stderr, "bad central directory entry %d\n", i);
213 return NULL;
214 }
215
216 int clen = Read4(cd+20); // compressed len
217 int ulen = Read4(cd+24); // uncompressed len
218 int nlen = Read2(cd+28); // filename len
219 int xlen = Read2(cd+30); // extra field len
220 int mlen = Read2(cd+32); // file comment len
221 int hoffset = Read4(cd+42); // local header offset
222
223 char* filename = malloc(nlen+1);
224 memcpy(filename, cd+46, nlen);
225 filename[nlen] = '\0';
226
227 int method = Read2(cd+10);
228
229 cd += 46 + nlen + xlen + mlen;
230
231 if (method != 8) { // 8 == deflate
232 free(filename);
233 continue;
234 }
235
236 unsigned char* lh = img + hoffset;
237
238 if (!(lh[0] == 0x50 && lh[1] == 0x4b && lh[2] == 0x03 && lh[3] == 0x04)) {
239 fprintf(stderr, "bad local file header entry %d\n", i);
240 return NULL;
241 }
242
243 if (Read2(lh+26) != nlen || memcmp(lh+30, filename, nlen) != 0) {
244 fprintf(stderr, "central dir filename doesn't match local header\n");
245 return NULL;
246 }
247
248 xlen = Read2(lh+28); // extra field len; might be different from CD entry?
249
250 temp_entries[entrycount].data_offset = hoffset+30+nlen+xlen;
251 temp_entries[entrycount].deflate_len = clen;
252 temp_entries[entrycount].uncomp_len = ulen;
253 temp_entries[entrycount].filename = filename;
254 ++entrycount;
255 }
256
257 qsort(temp_entries, entrycount, sizeof(ZipFileEntry), fileentry_compare);
258
259#if 0
260 printf("found %d deflated entries\n", entrycount);
261 for (i = 0; i < entrycount; ++i) {
262 printf("off %10d len %10d unlen %10d %p %s\n",
263 temp_entries[i].data_offset,
264 temp_entries[i].deflate_len,
265 temp_entries[i].uncomp_len,
266 temp_entries[i].filename,
267 temp_entries[i].filename);
268 }
269#endif
270
271 *num_chunks = 0;
272 *chunks = malloc((entrycount*2+2) * sizeof(ImageChunk));
273 ImageChunk* curr = *chunks;
274
275 if (include_pseudo_chunk) {
276 curr->type = CHUNK_NORMAL;
277 curr->start = 0;
278 curr->len = st.st_size;
279 curr->data = img;
280 curr->filename = NULL;
281 ++curr;
282 ++*num_chunks;
283 }
284
285 int pos = 0;
286 int nextentry = 0;
287
288 while (pos < st.st_size) {
289 if (nextentry < entrycount && pos == temp_entries[nextentry].data_offset) {
290 curr->type = CHUNK_DEFLATE;
291 curr->start = pos;
292 curr->deflate_len = temp_entries[nextentry].deflate_len;
293 curr->deflate_data = img + pos;
294 curr->filename = temp_entries[nextentry].filename;
295
296 curr->len = temp_entries[nextentry].uncomp_len;
297 curr->data = malloc(curr->len);
298
299 z_stream strm;
300 strm.zalloc = Z_NULL;
301 strm.zfree = Z_NULL;
302 strm.opaque = Z_NULL;
303 strm.avail_in = curr->deflate_len;
304 strm.next_in = curr->deflate_data;
305
306 // -15 means we are decoding a 'raw' deflate stream; zlib will
307 // not expect zlib headers.
308 int ret = inflateInit2(&strm, -15);
309
310 strm.avail_out = curr->len;
311 strm.next_out = curr->data;
312 ret = inflate(&strm, Z_NO_FLUSH);
313 if (ret != Z_STREAM_END) {
314 fprintf(stderr, "failed to inflate \"%s\"; %d\n", curr->filename, ret);
315 return NULL;
316 }
317
318 inflateEnd(&strm);
319
320 pos += curr->deflate_len;
321 ++nextentry;
322 ++*num_chunks;
323 ++curr;
324 continue;
325 }
326
327 // use a normal chunk to take all the data up to the start of the
328 // next deflate section.
329
330 curr->type = CHUNK_NORMAL;
331 curr->start = pos;
332 if (nextentry < entrycount) {
333 curr->len = temp_entries[nextentry].data_offset - pos;
334 } else {
335 curr->len = st.st_size - pos;
336 }
337 curr->data = img + pos;
338 curr->filename = NULL;
339 pos += curr->len;
340
341 ++*num_chunks;
342 ++curr;
343 }
344
345 free(temp_entries);
346 return img;
347}
348
Doug Zongker02d444b2009-05-27 18:24:03 -0700349/*
350 * Read the given file and break it up into chunks, putting the number
351 * of chunks and their info in *num_chunks and **chunks,
352 * respectively. Returns a malloc'd block of memory containing the
353 * contents of the file; various pointers in the output chunk array
354 * will point into this block of memory. The caller should free the
355 * return value when done with all the chunks. Returns NULL on
356 * failure.
357 */
358unsigned char* ReadImage(const char* filename,
359 int* num_chunks, ImageChunk** chunks) {
360 struct stat st;
361 if (stat(filename, &st) != 0) {
362 fprintf(stderr, "failed to stat \"%s\": %s\n", filename, strerror(errno));
363 return NULL;
364 }
365
366 unsigned char* img = malloc(st.st_size + 4);
367 FILE* f = fopen(filename, "rb");
368 if (fread(img, 1, st.st_size, f) != st.st_size) {
369 fprintf(stderr, "failed to read \"%s\" %s\n", filename, strerror(errno));
370 fclose(f);
371 return NULL;
372 }
373 fclose(f);
374
375 // append 4 zero bytes to the data so we can always search for the
376 // four-byte string 1f8b0800 starting at any point in the actual
377 // file data, without special-casing the end of the data.
378 memset(img+st.st_size, 0, 4);
379
380 size_t pos = 0;
381
382 *num_chunks = 0;
383 *chunks = NULL;
384
385 while (pos < st.st_size) {
386 unsigned char* p = img+pos;
387
Doug Zongker02d444b2009-05-27 18:24:03 -0700388 if (st.st_size - pos >= 4 &&
389 p[0] == 0x1f && p[1] == 0x8b &&
390 p[2] == 0x08 && // deflate compression
391 p[3] == 0x00) { // no header flags
392 // 'pos' is the offset of the start of a gzip chunk.
393
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700394 *num_chunks += 3;
395 *chunks = realloc(*chunks, *num_chunks * sizeof(ImageChunk));
396 ImageChunk* curr = *chunks + (*num_chunks-3);
397
398 // create a normal chunk for the header.
399 curr->start = pos;
400 curr->type = CHUNK_NORMAL;
401 curr->len = GZIP_HEADER_LEN;
402 curr->data = p;
403
404 pos += curr->len;
405 p += curr->len;
406 ++curr;
407
408 curr->type = CHUNK_DEFLATE;
409 curr->filename = NULL;
Doug Zongker02d444b2009-05-27 18:24:03 -0700410
411 // We must decompress this chunk in order to discover where it
412 // ends, and so we can put the uncompressed data and its length
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700413 // into curr->data and curr->len.
Doug Zongker02d444b2009-05-27 18:24:03 -0700414
415 size_t allocated = 32768;
416 curr->len = 0;
417 curr->data = malloc(allocated);
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700418 curr->start = pos;
419 curr->deflate_data = p;
Doug Zongker02d444b2009-05-27 18:24:03 -0700420
421 z_stream strm;
422 strm.zalloc = Z_NULL;
423 strm.zfree = Z_NULL;
424 strm.opaque = Z_NULL;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700425 strm.avail_in = st.st_size - pos;
426 strm.next_in = p;
Doug Zongker02d444b2009-05-27 18:24:03 -0700427
428 // -15 means we are decoding a 'raw' deflate stream; zlib will
429 // not expect zlib headers.
430 int ret = inflateInit2(&strm, -15);
431
432 do {
433 strm.avail_out = allocated - curr->len;
434 strm.next_out = curr->data + curr->len;
435 ret = inflate(&strm, Z_NO_FLUSH);
436 curr->len = allocated - strm.avail_out;
437 if (strm.avail_out == 0) {
438 allocated *= 2;
439 curr->data = realloc(curr->data, allocated);
440 }
441 } while (ret != Z_STREAM_END);
442
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700443 curr->deflate_len = st.st_size - strm.avail_in - pos;
Doug Zongker02d444b2009-05-27 18:24:03 -0700444 inflateEnd(&strm);
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700445 pos += curr->deflate_len;
446 p += curr->deflate_len;
447 ++curr;
Doug Zongker02d444b2009-05-27 18:24:03 -0700448
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700449 // create a normal chunk for the footer
450
451 curr->type = CHUNK_NORMAL;
452 curr->start = pos;
453 curr->len = GZIP_FOOTER_LEN;
454 curr->data = img+pos;
455
456 pos += curr->len;
457 p += curr->len;
458 ++curr;
Doug Zongker02d444b2009-05-27 18:24:03 -0700459
460 // The footer (that we just skipped over) contains the size of
461 // the uncompressed data. Double-check to make sure that it
462 // matches the size of the data we got when we actually did
463 // the decompression.
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700464 size_t footer_size = Read4(p-4);
465 if (footer_size != curr[-2].len) {
Doug Zongker02d444b2009-05-27 18:24:03 -0700466 fprintf(stderr, "Error: footer size %d != decompressed size %d\n",
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700467 footer_size, curr[-2].len);
Doug Zongker02d444b2009-05-27 18:24:03 -0700468 free(img);
469 return NULL;
470 }
471 } else {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700472 // Reallocate the list for every chunk; we expect the number of
473 // chunks to be small (5 for typical boot and recovery images).
474 ++*num_chunks;
475 *chunks = realloc(*chunks, *num_chunks * sizeof(ImageChunk));
476 ImageChunk* curr = *chunks + (*num_chunks-1);
477 curr->start = pos;
478
Doug Zongker02d444b2009-05-27 18:24:03 -0700479 // 'pos' is not the offset of the start of a gzip chunk, so scan
480 // forward until we find a gzip header.
481 curr->type = CHUNK_NORMAL;
482 curr->data = p;
483
484 for (curr->len = 0; curr->len < (st.st_size - pos); ++curr->len) {
485 if (p[curr->len] == 0x1f &&
486 p[curr->len+1] == 0x8b &&
487 p[curr->len+2] == 0x08 &&
488 p[curr->len+3] == 0x00) {
489 break;
490 }
491 }
492 pos += curr->len;
493 }
494 }
495
496 return img;
497}
498
499#define BUFFER_SIZE 32768
500
501/*
502 * Takes the uncompressed data stored in the chunk, compresses it
503 * using the zlib parameters stored in the chunk, and checks that it
504 * matches exactly the compressed data we started with (also stored in
505 * the chunk). Return 0 on success.
506 */
507int TryReconstruction(ImageChunk* chunk, unsigned char* out) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700508 size_t p = 0;
509
510#if 0
511 fprintf(stderr, "trying %d %d %d %d %d\n",
512 chunk->level, chunk->method, chunk->windowBits,
513 chunk->memLevel, chunk->strategy);
514#endif
Doug Zongker02d444b2009-05-27 18:24:03 -0700515
516 z_stream strm;
517 strm.zalloc = Z_NULL;
518 strm.zfree = Z_NULL;
519 strm.opaque = Z_NULL;
520 strm.avail_in = chunk->len;
521 strm.next_in = chunk->data;
522 int ret;
523 ret = deflateInit2(&strm, chunk->level, chunk->method, chunk->windowBits,
524 chunk->memLevel, chunk->strategy);
525 do {
526 strm.avail_out = BUFFER_SIZE;
527 strm.next_out = out;
528 ret = deflate(&strm, Z_FINISH);
529 size_t have = BUFFER_SIZE - strm.avail_out;
530
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700531 if (memcmp(out, chunk->deflate_data+p, have) != 0) {
Doug Zongker02d444b2009-05-27 18:24:03 -0700532 // mismatch; data isn't the same.
533 deflateEnd(&strm);
534 return -1;
535 }
536 p += have;
537 } while (ret != Z_STREAM_END);
538 deflateEnd(&strm);
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700539 if (p != chunk->deflate_len) {
Doug Zongker02d444b2009-05-27 18:24:03 -0700540 // mismatch; ran out of data before we should have.
541 return -1;
542 }
543 return 0;
544}
545
546/*
547 * Verify that we can reproduce exactly the same compressed data that
548 * we started with. Sets the level, method, windowBits, memLevel, and
549 * strategy fields in the chunk to the encoding parameters needed to
550 * produce the right output. Returns 0 on success.
551 */
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700552int ReconstructDeflateChunk(ImageChunk* chunk) {
553 if (chunk->type != CHUNK_DEFLATE) {
554 fprintf(stderr, "attempt to reconstruct non-deflate chunk\n");
Doug Zongker02d444b2009-05-27 18:24:03 -0700555 return -1;
556 }
557
558 size_t p = 0;
559 unsigned char* out = malloc(BUFFER_SIZE);
560
561 // We only check two combinations of encoder parameters: level 6
562 // (the default) and level 9 (the maximum).
563 for (chunk->level = 6; chunk->level <= 9; chunk->level += 3) {
564 chunk->windowBits = -15; // 32kb window; negative to indicate a raw stream.
565 chunk->memLevel = 8; // the default value.
566 chunk->method = Z_DEFLATED;
567 chunk->strategy = Z_DEFAULT_STRATEGY;
568
569 if (TryReconstruction(chunk, out) == 0) {
570 free(out);
571 return 0;
572 }
573 }
574
575 free(out);
576 return -1;
577}
578
Doug Zongker02d444b2009-05-27 18:24:03 -0700579/*
580 * Given source and target chunks, compute a bsdiff patch between them
581 * by running bsdiff in a subprocess. Return the patch data, placing
582 * its length in *size. Return NULL on failure. We expect the bsdiff
583 * program to be in the path.
584 */
585unsigned char* MakePatch(ImageChunk* src, ImageChunk* tgt, size_t* size) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700586 if (tgt->type == CHUNK_NORMAL) {
587 if (tgt->len <= 160) {
588 tgt->type = CHUNK_RAW;
589 *size = tgt->len;
590 return tgt->data;
591 }
592 }
593
Doug Zongker02d444b2009-05-27 18:24:03 -0700594 char stemp[] = "/tmp/imgdiff-src-XXXXXX";
595 char ttemp[] = "/tmp/imgdiff-tgt-XXXXXX";
596 char ptemp[] = "/tmp/imgdiff-patch-XXXXXX";
597 mkstemp(stemp);
598 mkstemp(ttemp);
599 mkstemp(ptemp);
600
601 FILE* f = fopen(stemp, "wb");
602 if (f == NULL) {
603 fprintf(stderr, "failed to open src chunk %s: %s\n",
604 stemp, strerror(errno));
605 return NULL;
606 }
607 if (fwrite(src->data, 1, src->len, f) != src->len) {
608 fprintf(stderr, "failed to write src chunk to %s: %s\n",
609 stemp, strerror(errno));
610 return NULL;
611 }
612 fclose(f);
613
614 f = fopen(ttemp, "wb");
615 if (f == NULL) {
616 fprintf(stderr, "failed to open tgt chunk %s: %s\n",
617 ttemp, strerror(errno));
618 return NULL;
619 }
620 if (fwrite(tgt->data, 1, tgt->len, f) != tgt->len) {
621 fprintf(stderr, "failed to write tgt chunk to %s: %s\n",
622 ttemp, strerror(errno));
623 return NULL;
624 }
625 fclose(f);
626
627 char cmd[200];
628 sprintf(cmd, "bsdiff %s %s %s", stemp, ttemp, ptemp);
629 if (system(cmd) != 0) {
630 fprintf(stderr, "failed to run bsdiff: %s\n", strerror(errno));
631 return NULL;
632 }
633
634 struct stat st;
635 if (stat(ptemp, &st) != 0) {
636 fprintf(stderr, "failed to stat patch file %s: %s\n",
637 ptemp, strerror(errno));
638 return NULL;
639 }
640
641 unsigned char* data = malloc(st.st_size);
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700642
643 if (tgt->type == CHUNK_NORMAL && tgt->len <= st.st_size) {
644 unlink(stemp);
645 unlink(ttemp);
646 unlink(ptemp);
647
648 tgt->type = CHUNK_RAW;
649 *size = tgt->len;
650 return tgt->data;
651 }
652
Doug Zongker02d444b2009-05-27 18:24:03 -0700653 *size = st.st_size;
654
655 f = fopen(ptemp, "rb");
656 if (f == NULL) {
657 fprintf(stderr, "failed to open patch %s: %s\n", ptemp, strerror(errno));
658 return NULL;
659 }
660 if (fread(data, 1, st.st_size, f) != st.st_size) {
661 fprintf(stderr, "failed to read patch %s: %s\n", ptemp, strerror(errno));
662 return NULL;
663 }
664 fclose(f);
665
666 unlink(stemp);
667 unlink(ttemp);
668 unlink(ptemp);
669
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700670 tgt->source_start = src->start;
671 switch (tgt->type) {
672 case CHUNK_NORMAL:
673 tgt->source_len = src->len;
674 break;
675 case CHUNK_DEFLATE:
676 tgt->source_len = src->deflate_len;
677 tgt->source_uncompressed_len = src->len;
678 break;
679 }
680
Doug Zongker02d444b2009-05-27 18:24:03 -0700681 return data;
682}
683
684/*
685 * Cause a gzip chunk to be treated as a normal chunk (ie, as a blob
686 * of uninterpreted data). The resulting patch will likely be about
687 * as big as the target file, but it lets us handle the case of images
688 * where some gzip chunks are reconstructible but others aren't (by
689 * treating the ones that aren't as normal chunks).
690 */
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700691void ChangeDeflateChunkToNormal(ImageChunk* ch) {
692 if (ch->type != CHUNK_DEFLATE) return;
Doug Zongker02d444b2009-05-27 18:24:03 -0700693 ch->type = CHUNK_NORMAL;
694 free(ch->data);
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700695 ch->data = ch->deflate_data;
696 ch->len = ch->deflate_len;
Doug Zongker02d444b2009-05-27 18:24:03 -0700697}
698
Doug Zongker3b724362009-07-15 17:54:30 -0700699/*
700 * Return true if the data in the chunk is identical (including the
701 * compressed representation, for gzip chunks).
702 */
703int AreChunksEqual(ImageChunk* a, ImageChunk* b) {
704 if (a->type != b->type) return 0;
705
706 switch (a->type) {
707 case CHUNK_NORMAL:
708 return a->len == b->len && memcmp(a->data, b->data, a->len) == 0;
709
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700710 case CHUNK_DEFLATE:
711 return a->deflate_len == b->deflate_len &&
712 memcmp(a->deflate_data, b->deflate_data, a->deflate_len) == 0;
Doug Zongker3b724362009-07-15 17:54:30 -0700713
714 default:
715 fprintf(stderr, "unknown chunk type %d\n", a->type);
716 return 0;
717 }
718}
719
720/*
721 * Look for runs of adjacent normal chunks and compress them down into
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700722 * a single chunk. (Such runs can be produced when deflate chunks are
Doug Zongker3b724362009-07-15 17:54:30 -0700723 * changed to normal chunks.)
724 */
725void MergeAdjacentNormalChunks(ImageChunk* chunks, int* num_chunks) {
726 int out = 0;
727 int in_start = 0, in_end;
728 while (in_start < *num_chunks) {
729 if (chunks[in_start].type != CHUNK_NORMAL) {
730 in_end = in_start+1;
731 } else {
732 // in_start is a normal chunk. Look for a run of normal chunks
733 // that constitute a solid block of data (ie, each chunk begins
734 // where the previous one ended).
735 for (in_end = in_start+1;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700736 in_end < *num_chunks && chunks[in_end].type == CHUNK_NORMAL &&
Doug Zongker3b724362009-07-15 17:54:30 -0700737 (chunks[in_end].start ==
738 chunks[in_end-1].start + chunks[in_end-1].len &&
739 chunks[in_end].data ==
740 chunks[in_end-1].data + chunks[in_end-1].len);
741 ++in_end);
742 }
743
744 if (in_end == in_start+1) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700745#if 0
746 printf("chunk %d is now %d\n", in_start, out);
747#endif
Doug Zongker3b724362009-07-15 17:54:30 -0700748 if (out != in_start) {
749 memcpy(chunks+out, chunks+in_start, sizeof(ImageChunk));
750 }
751 } else {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700752#if 0
753 printf("collapse normal chunks %d-%d into %d\n", in_start, in_end-1, out);
754#endif
Doug Zongker3b724362009-07-15 17:54:30 -0700755
756 // Merge chunks [in_start, in_end-1] into one chunk. Since the
757 // data member of each chunk is just a pointer into an in-memory
758 // copy of the file, this can be done without recopying (the
759 // output chunk has the first chunk's start location and data
760 // pointer, and length equal to the sum of the input chunk
761 // lengths).
762 chunks[out].type = CHUNK_NORMAL;
763 chunks[out].start = chunks[in_start].start;
764 chunks[out].data = chunks[in_start].data;
765 chunks[out].len = chunks[in_end-1].len +
766 (chunks[in_end-1].start - chunks[in_start].start);
767 }
768
769 ++out;
770 in_start = in_end;
771 }
772 *num_chunks = out;
773}
774
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700775ImageChunk* FindChunkByName(const char* name,
776 ImageChunk* chunks, int num_chunks) {
777 int i;
778 for (i = 0; i < num_chunks; ++i) {
779 if (chunks[i].type == CHUNK_DEFLATE && chunks[i].filename &&
780 strcmp(name, chunks[i].filename) == 0) {
781 return chunks+i;
782 }
783 }
784 return NULL;
785}
786
Doug Zongker02d444b2009-05-27 18:24:03 -0700787int main(int argc, char** argv) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700788 if (argc != 4 && argc != 5) {
789 usage:
790 fprintf(stderr, "usage: %s [-z] <src-img> <tgt-img> <patch-file>\n",
791 argv[0]);
Doug Zongker02d444b2009-05-27 18:24:03 -0700792 return 2;
793 }
794
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700795 int zip_mode = 0;
796
797 if (strcmp(argv[1], "-z") == 0) {
798 zip_mode = 1;
799 --argc;
800 ++argv;
801 }
802
803
Doug Zongker02d444b2009-05-27 18:24:03 -0700804 int num_src_chunks;
805 ImageChunk* src_chunks;
Doug Zongker02d444b2009-05-27 18:24:03 -0700806 int num_tgt_chunks;
807 ImageChunk* tgt_chunks;
Doug Zongker02d444b2009-05-27 18:24:03 -0700808 int i;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700809
810 if (zip_mode) {
811 if (ReadZip(argv[1], &num_src_chunks, &src_chunks, 1) == NULL) {
812 fprintf(stderr, "failed to break apart source zip file\n");
Doug Zongker02d444b2009-05-27 18:24:03 -0700813 return 1;
814 }
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700815 if (ReadZip(argv[2], &num_tgt_chunks, &tgt_chunks, 0) == NULL) {
816 fprintf(stderr, "failed to break apart target zip file\n");
817 return 1;
818 }
819 } else {
820 if (ReadImage(argv[1], &num_src_chunks, &src_chunks) == NULL) {
821 fprintf(stderr, "failed to break apart source image\n");
822 return 1;
823 }
824 if (ReadImage(argv[2], &num_tgt_chunks, &tgt_chunks) == NULL) {
825 fprintf(stderr, "failed to break apart target image\n");
826 return 1;
827 }
828
829 // Verify that the source and target images have the same chunk
830 // structure (ie, the same sequence of deflate and normal chunks).
831
832 if (num_src_chunks != num_tgt_chunks) {
833 fprintf(stderr, "source and target don't have same number of chunks!\n");
834 return 1;
835 }
836 for (i = 0; i < num_src_chunks; ++i) {
837 if (src_chunks[i].type != tgt_chunks[i].type) {
838 fprintf(stderr, "source and target don't have same chunk "
839 "structure! (chunk %d)\n", i);
840 return 1;
841 }
842 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700843 }
844
Doug Zongker02d444b2009-05-27 18:24:03 -0700845 for (i = 0; i < num_tgt_chunks; ++i) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700846 if (tgt_chunks[i].type == CHUNK_DEFLATE) {
Doug Zongker3b724362009-07-15 17:54:30 -0700847 // Confirm that given the uncompressed chunk data in the target, we
848 // can recompress it and get exactly the same bits as are in the
849 // input target image. If this fails, treat the chunk as a normal
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700850 // non-deflated chunk.
851 if (ReconstructDeflateChunk(tgt_chunks+i) < 0) {
852 printf("failed to reconstruct target deflate chunk %d [%s]; "
853 "treating as normal\n", i, tgt_chunks[i].filename);
854 ChangeDeflateChunkToNormal(tgt_chunks+i);
855 if (zip_mode) {
856 ImageChunk* src = FindChunkByName(tgt_chunks[i].filename, src_chunks, num_src_chunks);
857 if (src) {
858 ChangeDeflateChunkToNormal(src);
859 }
860 } else {
861 ChangeDeflateChunkToNormal(src_chunks+i);
862 }
Doug Zongker3b724362009-07-15 17:54:30 -0700863 continue;
Doug Zongker02d444b2009-05-27 18:24:03 -0700864 }
Doug Zongker3b724362009-07-15 17:54:30 -0700865
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700866 // If two deflate chunks are identical (eg, the kernel has not
Doug Zongker3b724362009-07-15 17:54:30 -0700867 // changed between two builds), treat them as normal chunks.
868 // This makes applypatch much faster -- it can apply a trivial
869 // patch to the compressed data, rather than uncompressing and
870 // recompressing to apply the trivial patch to the uncompressed
871 // data.
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700872 ImageChunk* src;
873 if (zip_mode) {
874 src = FindChunkByName(tgt_chunks[i].filename, src_chunks, num_src_chunks);
875 } else {
876 src = src_chunks+i;
877 }
878
879 if (src == NULL || AreChunksEqual(tgt_chunks+i, src)) {
880 ChangeDeflateChunkToNormal(tgt_chunks+i);
881 if (src) {
882 ChangeDeflateChunkToNormal(src);
883 }
Doug Zongker3b724362009-07-15 17:54:30 -0700884 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700885 }
886 }
887
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700888 // Merging neighboring normal chunks.
889 if (zip_mode) {
890 // For zips, we only need to do this to the target: deflated
891 // chunks are matched via filename, and normal chunks are patched
892 // using the entire source file as the source.
893 MergeAdjacentNormalChunks(tgt_chunks, &num_tgt_chunks);
894 } else {
895 // For images, we need to maintain the parallel structure of the
896 // chunk lists, so do the merging in both the source and target
897 // lists.
898 MergeAdjacentNormalChunks(tgt_chunks, &num_tgt_chunks);
899 MergeAdjacentNormalChunks(src_chunks, &num_src_chunks);
900 if (num_src_chunks != num_tgt_chunks) {
901 // This shouldn't happen.
902 fprintf(stderr, "merging normal chunks went awry\n");
903 return 1;
904 }
Doug Zongker3b724362009-07-15 17:54:30 -0700905 }
906
Doug Zongker02d444b2009-05-27 18:24:03 -0700907 // Compute bsdiff patches for each chunk's data (the uncompressed
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700908 // data, in the case of deflate chunks).
Doug Zongker02d444b2009-05-27 18:24:03 -0700909
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700910 printf("Construct patches for %d chunks...\n", num_tgt_chunks);
911 unsigned char** patch_data = malloc(num_tgt_chunks * sizeof(unsigned char*));
912 size_t* patch_size = malloc(num_tgt_chunks * sizeof(size_t));
913 for (i = 0; i < num_tgt_chunks; ++i) {
914 if (zip_mode) {
915 ImageChunk* src;
916 if (tgt_chunks[i].type == CHUNK_DEFLATE &&
917 (src = FindChunkByName(tgt_chunks[i].filename, src_chunks,
918 num_src_chunks))) {
919 patch_data[i] = MakePatch(src, tgt_chunks+i, patch_size+i);
920 } else {
921 patch_data[i] = MakePatch(src_chunks, tgt_chunks+i, patch_size+i);
922 }
923 } else {
924 patch_data[i] = MakePatch(src_chunks+i, tgt_chunks+i, patch_size+i);
925 }
926 printf("patch %3d is %d bytes (of %d)\n",
927 i, patch_size[i], tgt_chunks[i].source_len);
Doug Zongker02d444b2009-05-27 18:24:03 -0700928 }
929
930 // Figure out how big the imgdiff file header is going to be, so
931 // that we can correctly compute the offset of each bsdiff patch
932 // within the file.
933
934 size_t total_header_size = 12;
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700935 for (i = 0; i < num_tgt_chunks; ++i) {
936 total_header_size += 4;
937 switch (tgt_chunks[i].type) {
938 case CHUNK_NORMAL:
939 total_header_size += 8*3;
940 break;
941 case CHUNK_DEFLATE:
942 total_header_size += 8*5 + 4*5;
943 break;
944 case CHUNK_RAW:
945 total_header_size += 4 + patch_size[i];
946 break;
Doug Zongker02d444b2009-05-27 18:24:03 -0700947 }
948 }
949
950 size_t offset = total_header_size;
951
952 FILE* f = fopen(argv[3], "wb");
953
954 // Write out the headers.
955
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700956 fwrite("IMGDIFF2", 1, 8, f);
957 Write4(num_tgt_chunks, f);
Doug Zongker02d444b2009-05-27 18:24:03 -0700958 for (i = 0; i < num_tgt_chunks; ++i) {
959 Write4(tgt_chunks[i].type, f);
Doug Zongker02d444b2009-05-27 18:24:03 -0700960
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700961 switch (tgt_chunks[i].type) {
962 case CHUNK_NORMAL:
963 printf("chunk %3d: normal (%10d, %10d) %10d\n", i,
964 tgt_chunks[i].start, tgt_chunks[i].len, patch_size[i]);
965 Write8(tgt_chunks[i].source_start, f);
966 Write8(tgt_chunks[i].source_len, f);
967 Write8(offset, f);
968 offset += patch_size[i];
969 break;
970
971 case CHUNK_DEFLATE:
972 printf("chunk %3d: deflate (%10d, %10d) %10d %s\n", i,
973 tgt_chunks[i].start, tgt_chunks[i].deflate_len, patch_size[i],
974 tgt_chunks[i].filename);
975 Write8(tgt_chunks[i].source_start, f);
976 Write8(tgt_chunks[i].source_len, f);
977 Write8(offset, f);
978 Write8(tgt_chunks[i].source_uncompressed_len, f);
979 Write8(tgt_chunks[i].len, f);
980 Write4(tgt_chunks[i].level, f);
981 Write4(tgt_chunks[i].method, f);
982 Write4(tgt_chunks[i].windowBits, f);
983 Write4(tgt_chunks[i].memLevel, f);
984 Write4(tgt_chunks[i].strategy, f);
985 offset += patch_size[i];
986 break;
987
988 case CHUNK_RAW:
989 printf("chunk %3d: raw (%10d, %10d)\n", i,
990 tgt_chunks[i].start, tgt_chunks[i].len);
991 Write4(patch_size[i], f);
992 fwrite(patch_data[i], 1, patch_size[i], f);
993 break;
Doug Zongker02d444b2009-05-27 18:24:03 -0700994 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700995 }
996
997 // Append each chunk's bsdiff patch, in order.
998
999 for (i = 0; i < num_tgt_chunks; ++i) {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -07001000 if (tgt_chunks[i].type != CHUNK_RAW) {
1001 fwrite(patch_data[i], 1, patch_size[i], f);
1002 }
Doug Zongker02d444b2009-05-27 18:24:03 -07001003 }
1004
1005 fclose(f);
1006
1007 return 0;
1008}