1 /* xdelta 3 - delta compression tools and library
2 * Copyright (C) 2001, 2003, 2004, 2005, 2006, 2007,
3 * 2008, 2009, 2010, 2011, 2012, 2013. Joshua P. MacDonald
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 /* To know more about Xdelta, start by reading xdelta3.c. If you are
21 * ready to use the API, continue reading here. There are two
22 * interfaces -- xd3_encode_input and xd3_decode_input -- plus a dozen
23 * or so related calls. This interface is styled after Zlib. */
29 #define _ISOC99_SOURCE
42 #include <sys/types.h>
44 /****************************************************************/
46 /* Default configured value of stream->winsize. If the program
47 * supplies xd3_encode_input() with data smaller than winsize the
48 * stream will automatically buffer the input, otherwise the input
49 * buffer is used directly.
51 #ifndef XD3_DEFAULT_WINSIZE
52 #define XD3_DEFAULT_WINSIZE (1U << 23)
55 /* Default total size of the source window used in xdelta3-main.h */
56 #ifndef XD3_DEFAULT_SRCWINSZ
57 #define XD3_DEFAULT_SRCWINSZ (1U << 26)
60 /* When Xdelta requests a memory allocation for certain buffers, it
61 * rounds up to units of at least this size. The code assumes (and
62 * asserts) that this is a power-of-two. */
64 #define XD3_ALLOCSIZE (1U<<14)
67 /* The XD3_HARDMAXWINSIZE parameter is a safety mechanism to protect
68 * decoders against malicious files. The decoder will never decode a
69 * window larger than this. If the file specifies VCD_TARGET the
70 * decoder may require two buffers of this size.
72 * 8-16MB is reasonable, probably don't need to go larger. */
73 #ifndef XD3_HARDMAXWINSIZE
74 #define XD3_HARDMAXWINSIZE (1U<<24)
76 /* The IOPT_SIZE value sets the size of a buffer used to batch
77 * overlapping copy instructions before they are optimized by picking
78 * the best non-overlapping ranges. The larger this buffer, the
79 * longer a forced xd3_srcwin_setup() decision is held off. Setting
80 * this value to 0 causes an unlimited buffer to be used. */
81 #ifndef XD3_DEFAULT_IOPT_SIZE
82 #define XD3_DEFAULT_IOPT_SIZE (1U<<15)
85 /* The maximum distance backward to search for small matches */
86 #ifndef XD3_DEFAULT_SPREVSZ
87 #define XD3_DEFAULT_SPREVSZ (1U<<18)
90 /* The default compression level
92 #ifndef XD3_DEFAULT_LEVEL
93 #define XD3_DEFAULT_LEVEL 3
96 #ifndef XD3_DEFAULT_SECONDARY_LEVEL
97 #define XD3_DEFAULT_SECONDARY_LEVEL 6
100 #ifndef XD3_USE_LARGEFILE64
101 #define XD3_USE_LARGEFILE64 1
104 /* Sizes and addresses within VCDIFF windows are represented as usize_t
106 * For source-file offsets and total file sizes, total input and
107 * output counts, the xoff_t type is used. The decoder and encoder
108 * generally check for overflow of the xoff_t size (this is tested at
109 * the 32bit boundary [xdelta3-test.h]).
114 #define WIN32_LEAN_AND_MEAN
115 #if XD3_USE_LARGEFILE64
116 /* 64 bit file offsets: uses GetFileSizeEx and SetFilePointerEx.
117 * requires Win2000 or newer version of WinNT */
118 #define WINVER 0x0500
119 #define _WIN32_WINNT 0x0500
121 /* 32 bit (DWORD) file offsets: uses GetFileSize and
122 * SetFilePointer. compatible with win9x-me and WinNT4 */
123 #define WINVER 0x0400
124 #define _WIN32_WINNT 0x0400
129 typedef signed int ssize_t;
131 typedef unsigned char uint8_t;
132 typedef unsigned short uint16_t;
133 typedef unsigned long uint32_t;
134 typedef ULONGLONG uint64_t;
136 /* For MSVC10 and above */
140 /* mingw32, lcc and watcom provide a proper header */
145 typedef uint32_t usize_t;
147 #if XD3_USE_LARGEFILE64
148 #define __USE_FILE_OFFSET64 1 /* GLIBC: for 64bit fileops, ... ? */
149 #ifndef _LARGEFILE_SOURCE
150 #define _LARGEFILE_SOURCE
152 #ifndef _FILE_OFFSET_BITS
153 #define _FILE_OFFSET_BITS 64
156 typedef uint64_t xoff_t;
157 #define SIZEOF_XOFF_T 8
158 #define SIZEOF_USIZE_T 4
160 #if SIZEOF_SIZE_T == 8
169 typedef uint32_t xoff_t;
170 #define SIZEOF_XOFF_T 4
171 #define SIZEOF_USIZE_T 4
175 #define USE_UINT32 (SIZEOF_USIZE_T == 4 || \
176 SIZEOF_XOFF_T == 4 || REGRESSION_TEST)
177 #define USE_UINT64 (SIZEOF_USIZE_T == 8 || \
178 SIZEOF_XOFF_T == 8 || REGRESSION_TEST)
181 #ifdef HAVE_ALIGNED_ACCESS_REQUIRED
182 #define UNALIGNED_OK 0
184 /* This generally includes all Windows builds. */
185 #define UNALIGNED_OK 1
189 /**********************************************************************/
191 /* Whether to build the encoder, otherwise only build the decoder. */
193 #define XD3_ENCODER 1
196 /* The code returned when main() fails, also defined in system
199 #define EXIT_FAILURE 1
202 /* REGRESSION TEST enables the "xdelta3 test" command, which runs a
203 series of self-tests. */
204 #ifndef REGRESSION_TEST
205 #define REGRESSION_TEST 0
208 /* XD3_DEBUG=1 enables assertions and various statistics. Levels > 1
209 * enable some additional output only useful during development and
215 #ifndef PYTHON_MODULE
216 #define PYTHON_MODULE 0
220 #define SWIG_MODULE 0
223 /* There are three string matching functions supplied: one fast, one
224 * slow (default), and one soft-configurable. To disable any of
225 * these, use the following definitions. */
226 #ifndef XD3_BUILD_SLOW
227 #define XD3_BUILD_SLOW 1
229 #ifndef XD3_BUILD_FAST
230 #define XD3_BUILD_FAST 1
232 #ifndef XD3_BUILD_FASTER
233 #define XD3_BUILD_FASTER 1
235 #ifndef XD3_BUILD_FASTEST
236 #define XD3_BUILD_FASTEST 1
238 #ifndef XD3_BUILD_SOFT
239 #define XD3_BUILD_SOFT 1
241 #ifndef XD3_BUILD_DEFAULT
242 #define XD3_BUILD_DEFAULT 1
249 /* XPRINT. Debug output and VCDIFF_TOOLS functions report to stderr.
250 * I have used an irregular style to abbreviate [fprintf(stderr, "] as
255 typedef struct _xd3_stream xd3_stream;
256 typedef struct _xd3_source xd3_source;
257 typedef struct _xd3_hash_cfg xd3_hash_cfg;
258 typedef struct _xd3_smatcher xd3_smatcher;
259 typedef struct _xd3_rinst xd3_rinst;
260 typedef struct _xd3_dinst xd3_dinst;
261 typedef struct _xd3_hinst xd3_hinst;
262 typedef struct _xd3_winst xd3_winst;
263 typedef struct _xd3_rpage xd3_rpage;
264 typedef struct _xd3_addr_cache xd3_addr_cache;
265 typedef struct _xd3_output xd3_output;
266 typedef struct _xd3_desect xd3_desect;
267 typedef struct _xd3_iopt_buflist xd3_iopt_buflist;
268 typedef struct _xd3_rlist xd3_rlist;
269 typedef struct _xd3_sec_type xd3_sec_type;
270 typedef struct _xd3_sec_cfg xd3_sec_cfg;
271 typedef struct _xd3_sec_stream xd3_sec_stream;
272 typedef struct _xd3_config xd3_config;
273 typedef struct _xd3_code_table_desc xd3_code_table_desc;
274 typedef struct _xd3_code_table_sizes xd3_code_table_sizes;
275 typedef struct _xd3_slist xd3_slist;
276 typedef struct _xd3_whole_state xd3_whole_state;
277 typedef struct _xd3_wininfo xd3_wininfo;
279 /* The stream configuration has three callbacks functions, all of
280 * which may be supplied with NULL values. If config->getblk is
281 * provided as NULL, the stream returns XD3_GETSRCBLK. */
283 typedef void* (xd3_alloc_func) (void *opaque,
286 typedef void (xd3_free_func) (void *opaque,
289 typedef int (xd3_getblk_func) (xd3_stream *stream,
293 /* These are internal functions to delay construction of encoding
294 * tables and support alternate code tables. See the comments & code
295 * enabled by GENERIC_ENCODE_TABLES. */
297 typedef const xd3_dinst* (xd3_code_table_func) (void);
298 typedef int (xd3_comp_table_func) (xd3_stream *stream,
299 const uint8_t **data,
305 #define XD3_ASSERT(x) \
306 do { if (! (x)) { DP(RINT "%s:%d: XD3 assertion failed: %s\n", __FILE__, __LINE__, #x); \
307 abort (); } } while (0)
309 #define XD3_ASSERT(x) (void)0
310 #endif /* XD3_DEBUG */
313 #define max(x,y) ((x) < (y) ? (y) : (x))
316 #define min(x,y) ((x) < (y) ? (x) : (y))
319 /****************************************************************
321 ******************************************************************/
323 /* These are the five ordinary status codes returned by the
324 * xd3_encode_input() and xd3_decode_input() state machines. */
327 /* An application must be prepared to handle these five return
328 * values from either xd3_encode_input or xd3_decode_input, except
329 * in the case of no-source compression, in which case XD3_GETSRCBLK
330 * is never returned. More detailed comments for these are given in
331 * xd3_encode_input and xd3_decode_input comments, below. */
332 XD3_INPUT = -17703, /* need input */
333 XD3_OUTPUT = -17704, /* have output */
334 XD3_GETSRCBLK = -17705, /* need a block of source input (with no
335 * xd3_getblk function), a chance to do
336 * non-blocking read. */
337 XD3_GOTHEADER = -17706, /* (decode-only) after the initial VCDIFF &
338 first window header */
339 XD3_WINSTART = -17707, /* notification: returned before a window is
340 * processed, giving a chance to
341 * XD3_SKIP_WINDOW or not XD3_SKIP_EMIT that
343 XD3_WINFINISH = -17708, /* notification: returned after
344 encode/decode & output for a window */
345 XD3_TOOFARBACK = -17709, /* (encoder only) may be returned by
346 getblk() if the block is too old */
347 XD3_INTERNAL = -17710, /* internal error */
348 XD3_INVALID = -17711, /* invalid config */
349 XD3_INVALID_INPUT = -17712, /* invalid input/decoder error */
350 XD3_NOSECOND = -17713, /* when secondary compression finds no
352 XD3_UNIMPLEMENTED = -17714 /* currently VCD_TARGET, VCD_CODETABLE */
355 /* special values in config->flags */
358 XD3_JUST_HDR = (1 << 1), /* used by VCDIFF tools, see
360 XD3_SKIP_WINDOW = (1 << 2), /* used by VCDIFF tools, see
362 XD3_SKIP_EMIT = (1 << 3), /* used by VCDIFF tools, see
364 XD3_FLUSH = (1 << 4), /* flush the stream buffer to
366 xd3_stream_close(). */
368 XD3_SEC_DJW = (1 << 5), /* use DJW static huffman */
369 XD3_SEC_FGK = (1 << 6), /* use FGK adaptive huffman */
370 XD3_SEC_LZMA = (1 << 24), /* use LZMA secondary */
372 XD3_SEC_TYPE = (XD3_SEC_DJW | XD3_SEC_FGK | XD3_SEC_LZMA),
374 XD3_SEC_NODATA = (1 << 7), /* disable secondary compression of
376 XD3_SEC_NOINST = (1 << 8), /* disable secondary compression of
378 XD3_SEC_NOADDR = (1 << 9), /* disable secondary compression of
381 XD3_SEC_NOALL = (XD3_SEC_NODATA | XD3_SEC_NOINST | XD3_SEC_NOADDR),
383 XD3_ADLER32 = (1 << 10), /* enable checksum computation in
385 XD3_ADLER32_NOVER = (1 << 11), /* disable checksum verification in
388 XD3_NOCOMPRESS = (1 << 13), /* disable ordinary data
389 * compression feature, only search
390 * the source, not the target. */
391 XD3_BEGREEDY = (1 << 14), /* disable the "1.5-pass
392 * algorithm", instead use greedy
393 * matching. Greedy is off by
395 XD3_ADLER32_RECODE = (1 << 15), /* used by "recode". */
397 /* 4 bits to set the compression level the same as the command-line
398 * setting -1 through -9 (-0 corresponds to the XD3_NOCOMPRESS flag,
399 * and is independent of compression level). This is for
400 * convenience, especially with xd3_encode_memory(). */
402 XD3_COMPLEVEL_SHIFT = 20, /* 20 - 23 */
403 XD3_COMPLEVEL_MASK = (0xF << XD3_COMPLEVEL_SHIFT),
404 XD3_COMPLEVEL_1 = (1 << XD3_COMPLEVEL_SHIFT),
405 XD3_COMPLEVEL_2 = (2 << XD3_COMPLEVEL_SHIFT),
406 XD3_COMPLEVEL_3 = (3 << XD3_COMPLEVEL_SHIFT),
407 XD3_COMPLEVEL_6 = (6 << XD3_COMPLEVEL_SHIFT),
408 XD3_COMPLEVEL_9 = (9 << XD3_COMPLEVEL_SHIFT)
412 /* The values of this enumeration are set in xd3_config using the
413 * smatch_cfg variable. It can be set to default, slow, fast, etc.,
417 XD3_SMATCH_DEFAULT = 0, /* Flags may contain XD3_COMPLEVEL bits,
421 XD3_SMATCH_FASTER = 3,
422 XD3_SMATCH_FASTEST = 4,
426 /*********************************************************************
428 **********************************************************************/
430 /* stream->match_state is part of the xd3_encode_input state machine
431 * for source matching:
433 * 1. the XD3_GETSRCBLK block-read mechanism means reentrant matching
434 * 2. this state spans encoder windows: a match and end-of-window
435 * will continue in the next 3. the initial target byte and source
436 * byte are a presumed match, to avoid some computation in case the
437 * inputs are identical.
441 MATCH_TARGET = 0, /* in this state, attempt to match the start of
442 * the target with the previously set source
443 * address (initially 0). */
444 MATCH_BACKWARD = 1, /* currently expanding a match backward in the
446 MATCH_FORWARD = 2, /* currently expanding a match forward in the
448 MATCH_SEARCHING = 3 /* currently searching for a match. */
452 /* The xd3_encode_input state machine steps through these states in
453 * the following order. The matcher is reentrant and returns
454 * XD3_INPUT whenever it requires more data. After receiving
455 * XD3_INPUT, if the application reads EOF it should call
456 * xd3_stream_close().
460 ENC_INIT = 0, /* xd3_encode_input has never been called. */
461 ENC_INPUT = 1, /* waiting for xd3_avail_input () to be called. */
462 ENC_SEARCH = 2, /* currently searching for matches. */
463 ENC_INSTR = 3, /* currently formatting output. */
464 ENC_FLUSH = 4, /* currently emitting output. */
465 ENC_POSTOUT = 5, /* after an output section. */
466 ENC_POSTWIN = 6, /* after all output sections. */
467 ENC_ABORTED = 7 /* abort. */
470 /* The xd3_decode_input state machine steps through these states in
471 * the following order. The matcher is reentrant and returns
472 * XD3_INPUT whenever it requires more data. After receiving
473 * XD3_INPUT, if the application reads EOF it should call
474 * xd3_stream_close().
476 * 0-8: the VCDIFF header
477 * 9-18: the VCDIFF window header
478 * 19-21: the three primary sections: data, inst, addr
479 * 22: producing output: returns XD3_OUTPUT, possibly XD3_GETSRCBLK,
480 * 23: return XD3_WINFINISH, set state=9 to decode more input
484 DEC_VCHEAD = 0, /* VCDIFF header */
485 DEC_HDRIND = 1, /* header indicator */
487 DEC_SECONDID = 2, /* secondary compressor ID */
489 DEC_TABLEN = 3, /* code table length */
490 DEC_NEAR = 4, /* code table near */
491 DEC_SAME = 5, /* code table same */
492 DEC_TABDAT = 6, /* code table data */
494 DEC_APPLEN = 7, /* application data length */
495 DEC_APPDAT = 8, /* application data */
497 DEC_WININD = 9, /* window indicator */
499 DEC_CPYLEN = 10, /* copy window length */
500 DEC_CPYOFF = 11, /* copy window offset */
502 DEC_ENCLEN = 12, /* length of delta encoding */
503 DEC_TGTLEN = 13, /* length of target window */
504 DEC_DELIND = 14, /* delta indicator */
506 DEC_DATALEN = 15, /* length of ADD+RUN data */
507 DEC_INSTLEN = 16, /* length of instruction data */
508 DEC_ADDRLEN = 17, /* length of address data */
510 DEC_CKSUM = 18, /* window checksum */
512 DEC_DATA = 19, /* data section */
513 DEC_INST = 20, /* instruction section */
514 DEC_ADDR = 21, /* address section */
516 DEC_EMIT = 22, /* producing data */
518 DEC_FINISH = 23, /* window finished */
520 DEC_ABORTED = 24 /* xd3_abort_stream */
523 /************************************************************
525 ************************************************************/
527 /* instruction lists used in the IOPT buffer */
534 /* the raw encoding of an instruction used in the IOPT buffer */
547 /* the code-table form of an single- or double-instruction */
556 /* the decoded form of a single (half) instruction. */
560 uint32_t size; /* TODO: why decode breaks if this is usize_t? */
561 uint32_t addr; /* TODO: why decode breaks if this is usize_t? */
564 /* the form of a whole-file instruction */
567 uint8_t type; /* RUN, ADD, COPY */
568 uint8_t mode; /* 0, VCD_SOURCE, VCD_TARGET */
571 xoff_t position; /* absolute position of this inst */
574 /* used by the encoder to buffer output in sections. list of blocks. */
580 xd3_output *next_page;
583 /* used by the decoder to buffer input in sections. */
587 const uint8_t *buf_max;
588 uint32_t size; /* TODO: why decode breaks if this is usize_t? */
591 /* used in xdelta3-decode.h */
595 /* used in xdelta3-second.h */
600 /* the VCDIFF address cache, see the RFC */
601 struct _xd3_addr_cache
605 usize_t next_slot; /* the circular index for near */
606 usize_t *near_array; /* array of size s_near */
607 usize_t *same_array; /* array of size s_same*256 */
610 /* the IOPT buffer list is just a list of buffers, which may be allocated
611 * during encode when using an unlimited buffer. */
612 struct _xd3_iopt_buflist
615 xd3_iopt_buflist *next;
618 /* This is the record of a pre-compiled configuration, a subset of
623 int (*string_match) (xd3_stream *stream);
628 usize_t small_lchain;
633 /* hash table size & power-of-two hash function. */
647 /* window info (for whole state) */
648 struct _xd3_wininfo {
654 /* whole state for, e.g., merge */
655 struct _xd3_whole_state {
665 xd3_wininfo *wininfo;
666 usize_t wininfo_alloc;
671 /********************************************************************
673 *******************************************************************/
675 /* Settings for the secondary compressor. */
678 int data_type; /* Which section. (set automatically) */
679 usize_t ngroups; /* Number of DJW Huffman groups. */
680 usize_t sector_size; /* Sector size. */
681 int inefficient; /* If true, ignore efficiency check [avoid XD3_NOSECOND]. */
684 /* This is the user-visible stream configuration. */
687 usize_t winsize; /* The encoder window size. */
688 usize_t sprevsz; /* How far back small string
690 usize_t iopt_size; /* entries in the
691 instruction-optimizing
694 xd3_getblk_func *getblk; /* The three callbacks. */
695 xd3_alloc_func *alloc;
696 xd3_free_func *freef;
697 void *opaque; /* Not used. */
698 int flags; /* stream->flags are initialized
699 * from xd3_config & never
700 * modified by the library. Use
701 * xd3_set_flags to modify flags
702 * settings mid-stream. */
704 xd3_sec_cfg sec_data; /* Secondary compressor config: data */
705 xd3_sec_cfg sec_inst; /* Secondary compressor config: inst */
706 xd3_sec_cfg sec_addr; /* Secondary compressor config: addr */
708 xd3_smatch_cfg smatch_cfg; /* See enum: use fields below for
710 xd3_smatcher smatcher_soft;
713 /* The primary source file object. You create one of these objects and
714 * initialize the first four fields. This library maintains the next
715 * 5 fields. The configured getblk implementation is responsible for
716 * setting the final 3 fields when called (and/or when XD3_GETSRCBLK
722 usize_t blksize; /* block size */
723 const char *name; /* its name, for debug/print
725 void *ioh; /* opaque handle */
726 xoff_t max_winsize; /* maximum visible buffer */
729 xoff_t curblkno; /* current block number: client
730 sets after getblk request */
731 usize_t onblk; /* number of bytes on current
732 block: client sets, must be >= 0
734 const uint8_t *curblk; /* current block array: client
735 sets after getblk request */
738 usize_t srclen; /* length of this source window */
739 xoff_t srcbase; /* offset of this source window
740 in the source itself */
741 int shiftby; /* for power-of-two blocksizes */
742 int maskby; /* for power-of-two blocksizes */
743 xoff_t cpyoff_blocks; /* offset of dec_cpyoff in blocks */
744 usize_t cpyoff_blkoff; /* offset of copy window in
746 xoff_t getblkno; /* request block number: xd3 sets
747 current getblk request */
749 /* See xd3_getblk() */
750 xoff_t max_blkno; /* Maximum block, if eof is known,
751 * otherwise, equals frontier_blkno
753 xoff_t frontier_blkno; /* If eof is unknown, the next
754 * source position to be read.
755 * Otherwise, equal to
757 usize_t onlastblk; /* Number of bytes on max_blkno */
758 int eof_known; /* Set to true when the first
759 * partial block is read. */
762 /* The primary xd3_stream object, used for encoding and decoding. You
763 * may access only two fields: avail_out, next_out. Use the methods
764 * above to operate on xd3_stream. */
768 const uint8_t *next_in; /* next input byte */
769 usize_t avail_in; /* number of bytes available at
771 xoff_t total_in; /* how many bytes in */
774 uint8_t *next_out; /* next output byte */
775 usize_t avail_out; /* number of bytes available at
777 usize_t space_out; /* total out space */
778 xoff_t current_window; /* number of windows encoded/decoded */
779 xoff_t total_out; /* how many bytes out */
781 /* to indicate an error, xd3 sets */
782 const char *msg; /* last error message, NULL if
785 /* source configuration */
786 xd3_source *src; /* source array */
788 /* encoder memory configuration */
789 usize_t winsize; /* suggested window size */
790 usize_t sprevsz; /* small string, previous window
792 usize_t sprevmask; /* small string, previous window
795 usize_t iopt_unlimited;
797 /* general configuration */
798 xd3_getblk_func *getblk; /* set nxtblk, nxtblkno to scanblkno */
799 xd3_alloc_func *alloc; /* malloc function */
800 xd3_free_func *free; /* free function */
801 void* opaque; /* private data object passed to
802 alloc, free, and getblk */
803 int flags; /* various options */
805 /* secondary compressor configuration */
806 xd3_sec_cfg sec_data; /* Secondary compressor config: data */
807 xd3_sec_cfg sec_inst; /* Secondary compressor config: inst */
808 xd3_sec_cfg sec_addr; /* Secondary compressor config: addr */
810 xd3_smatcher smatcher;
812 usize_t *large_table; /* table of large checksums */
813 xd3_hash_cfg large_hash; /* large hash config */
815 usize_t *small_table; /* table of small checksums */
816 xd3_slist *small_prev; /* table of previous offsets,
817 circular linked list */
818 int small_reset; /* true if small table should
821 xd3_hash_cfg small_hash; /* small hash config */
822 xd3_addr_cache acache; /* the vcdiff address cache */
823 xd3_encode_state enc_state; /* state of the encoder */
825 usize_t taroff; /* base offset of the target input */
826 usize_t input_position; /* current input position */
827 usize_t min_match; /* current minimum match
828 length, avoids redundent
830 usize_t unencoded_offset; /* current input, first
831 * unencoded offset. this value
832 * is <= the first instruction's
833 * position in the iopt buffer,
834 * if there is at least one
835 * match in the buffer. */
838 int srcwin_decided; /* boolean: true if srclen and
841 int srcwin_decided_early; /* boolean: true if srclen
844 xoff_t srcwin_cksum_pos; /* Source checksum position */
847 xd3_match_state match_state; /* encoder match state */
848 xoff_t match_srcpos; /* current match source
851 xoff_t match_last_srcpos; /* previously attempted
852 * srcpos, to avoid loops. */
853 xoff_t match_minaddr; /* smallest matching address to
854 * set window params (reset each
855 * window xd3_encode_reset) */
856 xoff_t match_maxaddr; /* largest matching address to
857 * set window params (reset each
858 * window xd3_encode_reset) */
859 usize_t match_back; /* match extends back so far */
860 usize_t match_maxback; /* match extends back maximum */
861 usize_t match_fwd; /* match extends forward so far */
862 usize_t match_maxfwd; /* match extends forward maximum */
864 xoff_t maxsrcaddr; /* address of the last source
865 match (across windows) */
867 uint8_t *buf_in; /* for saving buffered input */
868 usize_t buf_avail; /* amount of saved input */
869 const uint8_t *buf_leftover; /* leftover content of next_in
870 (i.e., user's buffer) */
871 usize_t buf_leftavail; /* amount of leftover content */
873 xd3_output *enc_current; /* current output buffer */
874 xd3_output *enc_free; /* free output buffers */
875 xd3_output *enc_heads[4]; /* array of encoded outputs:
877 xd3_output *enc_tails[4]; /* array of encoded outputs:
879 uint32_t recode_adler32; /* set the adler32 checksum
880 * during "recode". */
882 xd3_rlist iopt_used; /* instruction optimizing buffer */
884 xd3_rinst *iout; /* next single instruction */
885 xd3_iopt_buflist *iopt_alloc;
887 const uint8_t *enc_appheader; /* application header to encode */
888 usize_t enc_appheadsz; /* application header size */
891 xd3_decode_state dec_state; /* current DEC_XXX value */
892 usize_t dec_hdr_ind; /* VCDIFF header indicator */
893 usize_t dec_win_ind; /* VCDIFF window indicator */
894 usize_t dec_del_ind; /* VCDIFF delta indicator */
896 uint8_t dec_magic[4]; /* First four bytes */
897 usize_t dec_magicbytes; /* Magic position. */
899 usize_t dec_secondid; /* Optional secondary compressor ID. */
901 /* TODO: why decode breaks if this is usize_t? */
902 uint32_t dec_codetblsz; /* Optional code table: length. */
903 uint8_t *dec_codetbl; /* Optional code table: storage. */
904 usize_t dec_codetblbytes; /* Optional code table: position. */
906 /* TODO: why decode breaks if this is usize_t? */
907 uint32_t dec_appheadsz; /* Optional application header:
909 uint8_t *dec_appheader; /* Optional application header:
911 usize_t dec_appheadbytes; /* Optional application header:
914 usize_t dec_cksumbytes; /* Optional checksum: position. */
915 uint8_t dec_cksum[4]; /* Optional checksum: storage. */
916 uint32_t dec_adler32; /* Optional checksum: value. */
918 /* TODO: why decode breaks if this is usize_t? */
919 uint32_t dec_cpylen; /* length of copy window
920 (VCD_SOURCE or VCD_TARGET) */
921 xoff_t dec_cpyoff; /* offset of copy window
922 (VCD_SOURCE or VCD_TARGET) */
923 /* TODO: why decode breaks if this is usize_t? */
924 uint32_t dec_enclen; /* length of delta encoding */
925 /* TODO: why decode breaks if this is usize_t? */
926 uint32_t dec_tgtlen; /* length of target window */
929 uint64_t dec_64part; /* part of a decoded uint64_t */
932 uint32_t dec_32part; /* part of a decoded uint32_t */
935 xoff_t dec_winstart; /* offset of the start of
936 current target window */
937 xoff_t dec_window_count; /* == current_window + 1 in
939 usize_t dec_winbytes; /* bytes of the three sections
941 usize_t dec_hdrsize; /* VCDIFF + app header size */
943 const uint8_t *dec_tgtaddrbase; /* Base of decoded target
946 const uint8_t *dec_cpyaddrbase; /* Base of decoded copy
950 usize_t dec_position; /* current decoder position
953 usize_t dec_maxpos; /* maximum decoder position
956 xd3_hinst dec_current1; /* current instruction */
957 xd3_hinst dec_current2; /* current instruction */
959 uint8_t *dec_buffer; /* Decode buffer */
960 uint8_t *dec_lastwin; /* In case of VCD_TARGET, the
961 last target window. */
962 usize_t dec_lastlen; /* length of the last target
964 xoff_t dec_laststart; /* offset of the start of last
966 usize_t dec_lastspace; /* allocated space of last
967 target window, for reuse */
969 xd3_desect inst_sect; /* staging area for decoding
971 xd3_desect addr_sect;
972 xd3_desect data_sect;
974 xd3_code_table_func *code_table_func;
975 xd3_comp_table_func *comp_table_func;
976 const xd3_dinst *code_table;
977 const xd3_code_table_desc *code_table_desc;
978 xd3_dinst *code_table_alloc;
980 /* secondary compression */
981 const xd3_sec_type *sec_type;
982 xd3_sec_stream *sec_stream_d;
983 xd3_sec_stream *sec_stream_i;
984 xd3_sec_stream *sec_stream_a;
986 /* state for reconstructing whole files (e.g., for merge), this only
987 * supports loading USIZE_T_MAX instructions, adds, etc. */
988 xd3_whole_state whole_target;
1001 usize_t i_slots_used;
1004 usize_t large_ckcnt;
1012 /**************************************************************************
1014 **************************************************************************/
1016 /* This function configures an xd3_stream using the provided in-memory
1017 * input buffer, source buffer, output buffer, and flags. The output
1018 * array must be large enough or else ENOSPC will be returned. This
1019 * is the simplest in-memory encoding interface. */
1020 int xd3_encode_memory (const uint8_t *input,
1022 const uint8_t *source,
1023 usize_t source_size,
1024 uint8_t *output_buffer,
1025 usize_t *output_size,
1026 usize_t avail_output,
1029 /* The reverse of xd3_encode_memory. */
1030 int xd3_decode_memory (const uint8_t *input,
1032 const uint8_t *source,
1033 usize_t source_size,
1034 uint8_t *output_buf,
1035 usize_t *output_size,
1036 usize_t avail_output,
1039 /* This function encodes an in-memory input using a pre-configured
1040 * xd3_stream. This allows the caller to set a variety of options
1041 * which are not available in the xd3_encode/decode_memory()
1044 * The output array must be large enough to hold the output or else
1045 * ENOSPC is returned. The source (if any) should be set using
1046 * xd3_set_source_and_size() with a single-block xd3_source. This
1047 * calls the underlying non-blocking interfaces,
1048 * xd3_encode/decode_input(), handling the necessary input/output
1049 * states. This method may be considered a reference for any
1050 * application using xd3_encode_input() directly.
1052 * xd3_stream stream;
1053 * xd3_config config;
1056 * memset (& src, 0, sizeof (src));
1057 * memset (& stream, 0, sizeof (stream));
1058 * memset (& config, 0, sizeof (config));
1060 * if (source != NULL)
1062 * src.size = source_size;
1063 * src.blksize = source_size;
1065 * src.onblk = source_size;
1066 * src.curblk = source;
1067 * src.max_winsize = source_size;
1068 * xd3_set_source(&stream, &src);
1071 * config.flags = flags;
1072 * config.winsize = input_size;
1074 * ... set smatcher, appheader, encoding-table, compression-level, etc.
1076 * xd3_config_stream(&stream, &config);
1077 * xd3_encode_stream(&stream, ...);
1078 * xd3_free_stream(&stream);
1080 int xd3_encode_stream (xd3_stream *stream,
1081 const uint8_t *input,
1084 usize_t *output_size,
1085 usize_t avail_output);
1087 /* The reverse of xd3_encode_stream. */
1088 int xd3_decode_stream (xd3_stream *stream,
1089 const uint8_t *input,
1092 usize_t *output_size,
1093 usize_t avail_size);
1095 /* This is the non-blocking interface.
1097 * Handling input and output states is the same for encoding or
1098 * decoding using the xd3_avail_input() and xd3_consume_output()
1099 * routines, inlined below.
1103 * XD3_INPUT: the process requires more input: call
1104 * xd3_avail_input() then repeat
1106 * XD3_OUTPUT: the process has more output: read stream->next_out,
1107 * stream->avail_out, then call xd3_consume_output(),
1110 * XD3_GOTHEADER: (decoder-only) notification returned following the
1111 * VCDIFF header and first window header. the decoder
1112 * may use the header to configure itself.
1114 * XD3_WINSTART: a general notification returned once for each
1115 * window except the 0-th window, which is implied by
1116 * XD3_GOTHEADER. It is recommended to use a
1117 * switch-stmt such as:
1121 * switch ((ret = xd3_decode_input (stream))) {
1122 * case XD3_GOTHEADER: {
1123 * assert(stream->current_window == 0);
1127 * case XD3_WINSTART: {
1128 * something(stream->current_window);
1133 * XD3_WINFINISH: a general notification, following the complete
1134 * input & output of a window. at this point,
1135 * stream->total_in and stream->total_out are consistent
1136 * for either encoding or decoding.
1138 * XD3_GETSRCBLK: If the xd3_getblk() callback is NULL, this value
1139 * is returned to initiate a non-blocking source read.
1141 int xd3_decode_input (xd3_stream *stream);
1142 int xd3_encode_input (xd3_stream *stream);
1144 /* The xd3_config structure is used to initialize a stream - all data
1145 * is copied into stream so config may be a temporary variable. See
1146 * the [documentation] or comments on the xd3_config structure. */
1147 int xd3_config_stream (xd3_stream *stream,
1148 xd3_config *config);
1150 /* Since Xdelta3 doesn't open any files, xd3_close_stream is just an
1151 * error check that the stream is in a proper state to be closed: this
1152 * means the encoder is flushed and the decoder is at a window
1153 * boundary. The application is responsible for freeing any of the
1154 * resources it supplied. */
1155 int xd3_close_stream (xd3_stream *stream);
1157 /* This arranges for closes the stream to succeed. Does not free the
1159 void xd3_abort_stream (xd3_stream *stream);
1161 /* xd3_free_stream frees all memory allocated for the stream. The
1162 * application is responsible for freeing any of the resources it
1164 void xd3_free_stream (xd3_stream *stream);
1166 /* This function informs the encoder or decoder that source matching
1167 * (i.e., delta-compression) is possible. For encoding, this should
1168 * be called before the first xd3_encode_input. A NULL source is
1169 * ignored. For decoding, this should be called before the first
1170 * window is decoded, but the appheader may be read first
1171 * (XD3_GOTHEADER). After decoding the header, call xd3_set_source()
1172 * if you have a source file. Note: if (stream->dec_win_ind & VCD_SOURCE)
1173 * is true, it means the first window expects there to be a source file.
1175 int xd3_set_source (xd3_stream *stream,
1176 xd3_source *source);
1178 /* If the source size is known, call this instead of xd3_set_source().
1179 * to avoid having stream->getblk called (and/or to avoid XD3_GETSRCBLK).
1181 * Follow these steps:
1183 memset(&source, 0, sizeof(source));
1184 source.blksize = size;
1185 source.onblk = size;
1186 source.curblk = buf;
1187 source.curblkno = 0;
1188 int ret = xd3_set_source_and_size(&stream, &source, size);
1191 int xd3_set_source_and_size (xd3_stream *stream,
1193 xoff_t source_size);
1195 /* This should be called before the first call to xd3_encode_input()
1196 * to include application-specific data in the VCDIFF header. */
1197 void xd3_set_appheader (xd3_stream *stream,
1198 const uint8_t *data,
1201 /* xd3_get_appheader may be called in the decoder after XD3_GOTHEADER.
1202 * For convenience, the decoder always adds a single byte padding to
1203 * the end of the application header, which is set to zero in case the
1204 * application header is a string. */
1205 int xd3_get_appheader (xd3_stream *stream,
1209 /* To generate a VCDIFF encoded delta with xd3_encode_init() from
1210 * another format, use:
1212 * xd3_encode_init_partial() -- initialze encoder state (w/o hash tables)
1213 * xd3_init_cache() -- reset VCDIFF address cache
1214 * xd3_found_match() -- to report a copy instruction
1216 * set stream->enc_state to ENC_INSTR and call xd3_encode_input as usual.
1218 int xd3_encode_init_partial (xd3_stream *stream);
1219 void xd3_init_cache (xd3_addr_cache* acache);
1220 int xd3_found_match (xd3_stream *stream,
1221 usize_t pos, usize_t size,
1222 xoff_t addr, int is_source);
1224 /* Gives an error string for xdelta3-speficic errors, returns NULL for
1226 const char* xd3_strerror (int ret);
1228 /* For convenience, zero & initialize the xd3_config structure with
1231 void xd3_init_config (xd3_config *config,
1234 memset (config, 0, sizeof (*config));
1235 config->flags = flags;
1238 /* This supplies some input to the stream.
1240 * For encoding, if the input is larger than the configured window
1241 * size (xd3_config.winsize), the entire input will be consumed and
1242 * encoded anyway. If you wish to strictly limit the window size,
1243 * limit the buffer passed to xd3_avail_input to the window size.
1245 * For encoding, if the input is smaller than the configured window
1246 * size (xd3_config.winsize), the library will create a window-sized
1247 * buffer and accumulate input until a full-sized window can be
1248 * encoded. XD3_INPUT will be returned. The input must remain valid
1249 * until the next time xd3_encode_input() returns XD3_INPUT.
1251 * For decoding, the input will be consumed entirely before XD3_INPUT
1252 * is returned again.
1255 void xd3_avail_input (xd3_stream *stream,
1256 const uint8_t *idata,
1259 /* Even if isize is zero, the code expects a non-NULL idata. Why?
1260 * It uses this value to determine whether xd3_avail_input has ever
1261 * been called. If xd3_encode_input is called before
1262 * xd3_avail_input it will return XD3_INPUT right away without
1263 * allocating a stream->winsize buffer. This is to avoid an
1264 * unwanted allocation. */
1265 XD3_ASSERT (idata != NULL || isize == 0);
1267 stream->next_in = idata;
1268 stream->avail_in = isize;
1271 /* This acknowledges receipt of output data, must be called after any
1272 * XD3_OUTPUT return. */
1274 void xd3_consume_output (xd3_stream *stream)
1276 stream->avail_out = 0;
1279 /* These are set for each XD3_WINFINISH return. */
1281 int xd3_encoder_used_source (xd3_stream *stream) {
1282 return stream->src != NULL && stream->src->srclen > 0;
1285 xoff_t xd3_encoder_srcbase (xd3_stream *stream) {
1286 return stream->src->srcbase;
1289 usize_t xd3_encoder_srclen (xd3_stream *stream) {
1290 return stream->src->srclen;
1293 /* Checks for legal flag changes. */
1295 void xd3_set_flags (xd3_stream *stream, int flags)
1297 /* The bitwise difference should contain only XD3_FLUSH or
1299 XD3_ASSERT(((flags ^ stream->flags) & ~(XD3_FLUSH | XD3_SKIP_WINDOW)) == 0);
1300 stream->flags = flags;
1303 /* Gives some extra information about the latest library error, if any
1306 const char* xd3_errstring (xd3_stream *stream)
1308 return stream->msg ? stream->msg : "";
1312 /* 64-bit divisions are expensive, which is why we require a
1313 * power-of-two source->blksize. To relax this restriction is
1314 * relatively easy, see the history for xd3_blksize_div(). */
1316 void xd3_blksize_div (const xoff_t offset,
1317 const xd3_source *source,
1320 *blkno = (xoff_t) (offset >> source->shiftby);
1321 *blkoff = (usize_t) (offset & source->maskby);
1322 XD3_ASSERT (*blkoff < source->blksize);
1326 void xd3_blksize_add (xoff_t *blkno,
1328 const xd3_source *source,
1333 /* Does not check for overflow, checked in xdelta3-decode.h. */
1335 blkdiff = *blkoff >> source->shiftby;
1340 *blkoff &= source->maskby;
1343 XD3_ASSERT (*blkoff < source->blksize);
1349 #define XD3_CPY 3U /* XD3_CPY rtypes are represented as (XD3_CPY +
1350 * copy-mode value) */
1353 #define IF_DEBUG(x) x
1358 #define IF_DEBUG1(x) x
1360 #define IF_DEBUG1(x)
1363 #define IF_DEBUG2(x) x
1365 #define IF_DEBUG2(x)
1368 #define SIZEOF_ARRAY(x) (sizeof(x) / sizeof(x[0]))
1370 #endif /* _XDELTA3_H_ */