Merge branch 'mm/push-social-engineering-attack-doc' into maint
[git/git-svn.git] / patch-delta.c
blob56e0a5ede22c9396fc897bf1d3444dce92d8916f
1 /*
2 * patch-delta.c:
3 * recreate a buffer from a source and the delta produced by diff-delta.c
5 * (C) 2005 Nicolas Pitre <nico@fluxnic.net>
7 * This code is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
12 #include "git-compat-util.h"
13 #include "delta.h"
15 void *patch_delta(const void *src_buf, unsigned long src_size,
16 const void *delta_buf, unsigned long delta_size,
17 unsigned long *dst_size)
19 const unsigned char *data, *top;
20 unsigned char *dst_buf, *out, cmd;
21 unsigned long size;
23 if (delta_size < DELTA_SIZE_MIN)
24 return NULL;
26 data = delta_buf;
27 top = (const unsigned char *) delta_buf + delta_size;
29 /* make sure the orig file size matches what we expect */
30 size = get_delta_hdr_size(&data, top);
31 if (size != src_size)
32 return NULL;
34 /* now the result size */
35 size = get_delta_hdr_size(&data, top);
36 dst_buf = xmallocz(size);
38 out = dst_buf;
39 while (data < top) {
40 cmd = *data++;
41 if (cmd & 0x80) {
42 unsigned long cp_off = 0, cp_size = 0;
43 if (cmd & 0x01) cp_off = *data++;
44 if (cmd & 0x02) cp_off |= (*data++ << 8);
45 if (cmd & 0x04) cp_off |= (*data++ << 16);
46 if (cmd & 0x08) cp_off |= ((unsigned) *data++ << 24);
47 if (cmd & 0x10) cp_size = *data++;
48 if (cmd & 0x20) cp_size |= (*data++ << 8);
49 if (cmd & 0x40) cp_size |= (*data++ << 16);
50 if (cp_size == 0) cp_size = 0x10000;
51 if (unsigned_add_overflows(cp_off, cp_size) ||
52 cp_off + cp_size > src_size ||
53 cp_size > size)
54 break;
55 memcpy(out, (char *) src_buf + cp_off, cp_size);
56 out += cp_size;
57 size -= cp_size;
58 } else if (cmd) {
59 if (cmd > size)
60 break;
61 memcpy(out, data, cmd);
62 out += cmd;
63 data += cmd;
64 size -= cmd;
65 } else {
67 * cmd == 0 is reserved for future encoding
68 * extensions. In the mean time we must fail when
69 * encountering them (might be data corruption).
71 error("unexpected delta opcode 0");
72 goto bad;
76 /* sanity check */
77 if (data != top || size != 0) {
78 error("delta replay has gone wild");
79 bad:
80 free(dst_buf);
81 return NULL;
84 *dst_size = out - dst_buf;
85 return dst_buf;