Merge branch 'cc/svn-fe-py-shebang'
[git/git.git] / patch-delta.c
CommitLineData
a310d434
NP
1/*
2 * patch-delta.c:
3 * recreate a buffer from a source and the delta produced by diff-delta.c
4 *
03aa8ff3 5 * (C) 2005 Nicolas Pitre <nico@fluxnic.net>
a310d434
NP
6 *
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.
10 */
11
57b73150 12#include "git-compat-util.h"
a310d434
NP
13#include "delta.h"
14
08abe669
NP
15void *patch_delta(const void *src_buf, unsigned long src_size,
16 const void *delta_buf, unsigned long delta_size,
a310d434
NP
17 unsigned long *dst_size)
18{
19 const unsigned char *data, *top;
20 unsigned char *dst_buf, *out, cmd;
21 unsigned long size;
a310d434 22
dcde55bc 23 if (delta_size < DELTA_SIZE_MIN)
a310d434
NP
24 return NULL;
25
26 data = delta_buf;
1d7f171c 27 top = (const unsigned char *) delta_buf + delta_size;
a310d434
NP
28
29 /* make sure the orig file size matches what we expect */
8960844a 30 size = get_delta_hdr_size(&data, top);
a310d434
NP
31 if (size != src_size)
32 return NULL;
33
34 /* now the result size */
8960844a 35 size = get_delta_hdr_size(&data, top);
222083a1 36 dst_buf = xmallocz(size);
a310d434
NP
37
38 out = dst_buf;
39 while (data < top) {
40 cmd = *data++;
41 if (cmd & 0x80) {
42 unsigned long cp_off = 0, cp_size = 0;
9514b0b2
JK
43#define PARSE_CP_PARAM(bit, var, shift) do { \
44 if (cmd & (bit)) { \
45 if (data >= top) \
46 goto bad_length; \
47 var |= ((unsigned) *data++ << (shift)); \
48 } } while (0)
49 PARSE_CP_PARAM(0x01, cp_off, 0);
50 PARSE_CP_PARAM(0x02, cp_off, 8);
51 PARSE_CP_PARAM(0x04, cp_off, 16);
52 PARSE_CP_PARAM(0x08, cp_off, 24);
53 PARSE_CP_PARAM(0x10, cp_size, 0);
54 PARSE_CP_PARAM(0x20, cp_size, 8);
55 PARSE_CP_PARAM(0x40, cp_size, 16);
56#undef PARSE_CP_PARAM
a310d434 57 if (cp_size == 0) cp_size = 0x10000;
1368f650 58 if (unsigned_add_overflows(cp_off, cp_size) ||
8960844a
NP
59 cp_off + cp_size > src_size ||
60 cp_size > size)
fa72f90e 61 goto bad_length;
1d7f171c 62 memcpy(out, (char *) src_buf + cp_off, cp_size);
a310d434 63 out += cp_size;
8960844a
NP
64 size -= cp_size;
65 } else if (cmd) {
21870efc 66 if (cmd > size || cmd > top - data)
fa72f90e 67 goto bad_length;
a310d434
NP
68 memcpy(out, data, cmd);
69 out += cmd;
70 data += cmd;
8960844a
NP
71 size -= cmd;
72 } else {
73 /*
74 * cmd == 0 is reserved for future encoding
75 * extensions. In the mean time we must fail when
76 * encountering them (might be data corruption).
77 */
57b73150 78 error("unexpected delta opcode 0");
8960844a 79 goto bad;
a310d434
NP
80 }
81 }
82
83 /* sanity check */
8960844a 84 if (data != top || size != 0) {
fa72f90e 85 bad_length:
57b73150 86 error("delta replay has gone wild");
8960844a 87 bad:
a310d434
NP
88 free(dst_buf);
89 return NULL;
90 }
91
8960844a 92 *dst_size = out - dst_buf;
a310d434
NP
93 return dst_buf;
94}