xref: /aosp_15_r20/external/xz-embedded/linux/include/linux/xz.h (revision d2c16535d139cb185e89120452531bba6b36d3c6)
1 /* SPDX-License-Identifier: 0BSD */
2 
3 /*
4  * XZ decompressor
5  *
6  * Authors: Lasse Collin <[email protected]>
7  *          Igor Pavlov <https://7-zip.org/>
8  */
9 
10 #ifndef XZ_H
11 #define XZ_H
12 
13 #ifdef __KERNEL__
14 #	include <linux/stddef.h>
15 #	include <linux/types.h>
16 #else
17 #	include <stddef.h>
18 #	include <stdint.h>
19 #endif
20 
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
24 
25 /* In Linux, this is used to make extern functions static when needed. */
26 #ifndef XZ_EXTERN
27 #	define XZ_EXTERN extern
28 #endif
29 
30 /**
31  * enum xz_mode - Operation mode
32  *
33  * @XZ_SINGLE:              Single-call mode. This uses less RAM than
34  *                          multi-call modes, because the LZMA2
35  *                          dictionary doesn't need to be allocated as
36  *                          part of the decoder state. All required data
37  *                          structures are allocated at initialization,
38  *                          so xz_dec_run() cannot return XZ_MEM_ERROR.
39  * @XZ_PREALLOC:            Multi-call mode with preallocated LZMA2
40  *                          dictionary buffer. All data structures are
41  *                          allocated at initialization, so xz_dec_run()
42  *                          cannot return XZ_MEM_ERROR.
43  * @XZ_DYNALLOC:            Multi-call mode. The LZMA2 dictionary is
44  *                          allocated once the required size has been
45  *                          parsed from the stream headers. If the
46  *                          allocation fails, xz_dec_run() will return
47  *                          XZ_MEM_ERROR.
48  *
49  * It is possible to enable support only for a subset of the above
50  * modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC,
51  * or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled
52  * with support for all operation modes, but the preboot code may
53  * be built with fewer features to minimize code size.
54  */
55 enum xz_mode {
56 	XZ_SINGLE,
57 	XZ_PREALLOC,
58 	XZ_DYNALLOC
59 };
60 
61 /**
62  * enum xz_ret - Return codes
63  * @XZ_OK:                  Everything is OK so far. More input or more
64  *                          output space is required to continue. This
65  *                          return code is possible only in multi-call mode
66  *                          (XZ_PREALLOC or XZ_DYNALLOC).
67  * @XZ_STREAM_END:          Operation finished successfully.
68  * @XZ_UNSUPPORTED_CHECK:   Integrity check type is not supported. Decoding
69  *                          is still possible in multi-call mode by simply
70  *                          calling xz_dec_run() again.
71  *                          Note that this return value is used only if
72  *                          XZ_DEC_ANY_CHECK was defined at build time,
73  *                          which is not used in the kernel. Unsupported
74  *                          check types return XZ_OPTIONS_ERROR if
75  *                          XZ_DEC_ANY_CHECK was not defined at build time.
76  * @XZ_MEM_ERROR:           Allocating memory failed. This return code is
77  *                          possible only if the decoder was initialized
78  *                          with XZ_DYNALLOC. The amount of memory that was
79  *                          tried to be allocated was no more than the
80  *                          dict_max argument given to xz_dec_init().
81  * @XZ_MEMLIMIT_ERROR:      A bigger LZMA2 dictionary would be needed than
82  *                          allowed by the dict_max argument given to
83  *                          xz_dec_init(). This return value is possible
84  *                          only in multi-call mode (XZ_PREALLOC or
85  *                          XZ_DYNALLOC); the single-call mode (XZ_SINGLE)
86  *                          ignores the dict_max argument.
87  * @XZ_FORMAT_ERROR:        File format was not recognized (wrong magic
88  *                          bytes).
89  * @XZ_OPTIONS_ERROR:       This implementation doesn't support the requested
90  *                          compression options. In the decoder this means
91  *                          that the header CRC32 matches, but the header
92  *                          itself specifies something that we don't support.
93  * @XZ_DATA_ERROR:          Compressed data is corrupt.
94  * @XZ_BUF_ERROR:           Cannot make any progress. Details are slightly
95  *                          different between multi-call and single-call
96  *                          mode; more information below.
97  *
98  * In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls
99  * to XZ code cannot consume any input and cannot produce any new output.
100  * This happens when there is no new input available, or the output buffer
101  * is full while at least one output byte is still pending. Assuming your
102  * code is not buggy, you can get this error only when decoding a compressed
103  * stream that is truncated or otherwise corrupt.
104  *
105  * In single-call mode, XZ_BUF_ERROR is returned only when the output buffer
106  * is too small or the compressed input is corrupt in a way that makes the
107  * decoder produce more output than the caller expected. When it is
108  * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR
109  * is used instead of XZ_BUF_ERROR.
110  */
111 enum xz_ret {
112 	XZ_OK,
113 	XZ_STREAM_END,
114 	XZ_UNSUPPORTED_CHECK,
115 	XZ_MEM_ERROR,
116 	XZ_MEMLIMIT_ERROR,
117 	XZ_FORMAT_ERROR,
118 	XZ_OPTIONS_ERROR,
119 	XZ_DATA_ERROR,
120 	XZ_BUF_ERROR
121 };
122 
123 /**
124  * struct xz_buf - Passing input and output buffers to XZ code
125  * @in:         Beginning of the input buffer. This may be NULL if and only
126  *              if in_pos is equal to in_size.
127  * @in_pos:     Current position in the input buffer. This must not exceed
128  *              in_size.
129  * @in_size:    Size of the input buffer
130  * @out:        Beginning of the output buffer. This may be NULL if and only
131  *              if out_pos is equal to out_size.
132  * @out_pos:    Current position in the output buffer. This must not exceed
133  *              out_size.
134  * @out_size:   Size of the output buffer
135  *
136  * Only the contents of the output buffer from out[out_pos] onward, and
137  * the variables in_pos and out_pos are modified by the XZ code.
138  */
139 struct xz_buf {
140 	const uint8_t *in;
141 	size_t in_pos;
142 	size_t in_size;
143 
144 	uint8_t *out;
145 	size_t out_pos;
146 	size_t out_size;
147 };
148 
149 /**
150  * struct xz_dec - Opaque type to hold the XZ decoder state
151  */
152 struct xz_dec;
153 
154 /**
155  * xz_dec_init() - Allocate and initialize a XZ decoder state
156  * @mode:       Operation mode
157  * @dict_max:   Maximum size of the LZMA2 dictionary (history buffer) for
158  *              multi-call decoding. This is ignored in single-call mode
159  *              (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes
160  *              or 2^n + 2^(n-1) bytes (the latter sizes are less common
161  *              in practice), so other values for dict_max don't make sense.
162  *              In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB,
163  *              512 KiB, and 1 MiB are probably the only reasonable values,
164  *              except for kernel and initramfs images where a bigger
165  *              dictionary can be fine and useful.
166  *
167  * Single-call mode (XZ_SINGLE): xz_dec_run() decodes the whole stream at
168  * once. The caller must provide enough output space or the decoding will
169  * fail. The output space is used as the dictionary buffer, which is why
170  * there is no need to allocate the dictionary as part of the decoder's
171  * internal state.
172  *
173  * Because the output buffer is used as the workspace, streams encoded using
174  * a big dictionary are not a problem in single-call mode. It is enough that
175  * the output buffer is big enough to hold the actual uncompressed data; it
176  * can be smaller than the dictionary size stored in the stream headers.
177  *
178  * Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes
179  * of memory is preallocated for the LZMA2 dictionary. This way there is no
180  * risk that xz_dec_run() could run out of memory, since xz_dec_run() will
181  * never allocate any memory. Instead, if the preallocated dictionary is too
182  * small for decoding the given input stream, xz_dec_run() will return
183  * XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be
184  * decoded to avoid allocating excessive amount of memory for the dictionary.
185  *
186  * Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC):
187  * dict_max specifies the maximum allowed dictionary size that xz_dec_run()
188  * may allocate once it has parsed the dictionary size from the stream
189  * headers. This way excessive allocations can be avoided while still
190  * limiting the maximum memory usage to a sane value to prevent running the
191  * system out of memory when decompressing streams from untrusted sources.
192  *
193  * On success, xz_dec_init() returns a pointer to struct xz_dec, which is
194  * ready to be used with xz_dec_run(). If memory allocation fails,
195  * xz_dec_init() returns NULL.
196  */
197 XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max);
198 
199 /**
200  * xz_dec_run() - Run the XZ decoder for a single XZ stream
201  * @s:          Decoder state allocated using xz_dec_init()
202  * @b:          Input and output buffers
203  *
204  * The possible return values depend on build options and operation mode.
205  * See enum xz_ret for details.
206  *
207  * Note that if an error occurs in single-call mode (return value is not
208  * XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the
209  * contents of the output buffer from b->out[b->out_pos] onward are
210  * undefined. This is true even after XZ_BUF_ERROR, because with some filter
211  * chains, there may be a second pass over the output buffer, and this pass
212  * cannot be properly done if the output buffer is truncated. Thus, you
213  * cannot give the single-call decoder a too small buffer and then expect to
214  * get that amount valid data from the beginning of the stream. You must use
215  * the multi-call decoder if you don't want to uncompress the whole stream.
216  *
217  * Use xz_dec_run() when XZ data is stored inside some other file format.
218  * The decoding will stop after one XZ stream has been decompressed. To
219  * decompress regular .xz files which might have multiple concatenated
220  * streams, use xz_dec_catrun() instead.
221  */
222 XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b);
223 
224 /**
225  * xz_dec_catrun() - Run the XZ decoder with support for concatenated streams
226  * @s:          Decoder state allocated using xz_dec_init()
227  * @b:          Input and output buffers
228  * @finish:     This is an int instead of bool to avoid requiring stdbool.h.
229  *              As long as more input might be coming, finish must be false.
230  *              When the caller knows that it has provided all the input to
231  *              the decoder (some possibly still in b->in), it must set finish
232  *              to true. Only when finish is true can this function return
233  *              XZ_STREAM_END to indicate successful decompression of the
234  *              file. In single-call mode (XZ_SINGLE) finish is assumed to
235  *              always be true; the caller-provided value is ignored.
236  *
237  * This is like xz_dec_run() except that this makes it easy to decode .xz
238  * files with multiple streams (multiple .xz files concatenated as is).
239  * The rarely-used Stream Padding feature is supported too, that is, there
240  * can be null bytes after or between the streams. The number of null bytes
241  * must be a multiple of four.
242  *
243  * When finish is false and b->in_pos == b->in_size, it is possible that
244  * XZ_BUF_ERROR isn't returned even when no progress is possible (XZ_OK is
245  * returned instead). This shouldn't matter because in this situation a
246  * reasonable caller will attempt to provide more input or set finish to
247  * true for the next xz_dec_catrun() call anyway.
248  *
249  * For any struct xz_dec that has been initialized for multi-call mode:
250  * Once decoding has been started with xz_dec_run() or xz_dec_catrun(),
251  * the same function must be used until xz_dec_reset() or xz_dec_end().
252  * Switching between the two decoding functions without resetting results
253  * in undefined behavior.
254  *
255  * xz_dec_catrun() is only available if XZ_DEC_CONCATENATED was defined
256  * at compile time.
257  */
258 XZ_EXTERN enum xz_ret xz_dec_catrun(struct xz_dec *s, struct xz_buf *b,
259 				    int finish);
260 
261 /**
262  * xz_dec_reset() - Reset an already allocated decoder state
263  * @s:          Decoder state allocated using xz_dec_init()
264  *
265  * This function can be used to reset the multi-call decoder state without
266  * freeing and reallocating memory with xz_dec_end() and xz_dec_init().
267  *
268  * In single-call mode, xz_dec_reset() is always called in the beginning of
269  * xz_dec_run(). Thus, explicit call to xz_dec_reset() is useful only in
270  * multi-call mode.
271  */
272 XZ_EXTERN void xz_dec_reset(struct xz_dec *s);
273 
274 /**
275  * xz_dec_end() - Free the memory allocated for the decoder state
276  * @s:          Decoder state allocated using xz_dec_init(). If s is NULL,
277  *              this function does nothing.
278  */
279 XZ_EXTERN void xz_dec_end(struct xz_dec *s);
280 
281 /*
282  * Decompressor for MicroLZMA, an LZMA variant with a very minimal header.
283  * See xz_dec_microlzma_alloc() below for details.
284  *
285  * These functions aren't used or available in preboot code and thus aren't
286  * marked with XZ_EXTERN. This avoids warnings about static functions that
287  * are never defined.
288  */
289 /**
290  * struct xz_dec_microlzma - Opaque type to hold the MicroLZMA decoder state
291  */
292 struct xz_dec_microlzma;
293 
294 /**
295  * xz_dec_microlzma_alloc() - Allocate memory for the MicroLZMA decoder
296  * @mode        XZ_SINGLE or XZ_PREALLOC
297  * @dict_size   LZMA dictionary size. This must be at least 4 KiB and
298  *              at most 3 GiB.
299  *
300  * In contrast to xz_dec_init(), this function only allocates the memory
301  * and remembers the dictionary size. xz_dec_microlzma_reset() must be used
302  * before calling xz_dec_microlzma_run().
303  *
304  * The amount of allocated memory is a little less than 30 KiB with XZ_SINGLE.
305  * With XZ_PREALLOC also a dictionary buffer of dict_size bytes is allocated.
306  *
307  * On success, xz_dec_microlzma_alloc() returns a pointer to
308  * struct xz_dec_microlzma. If memory allocation fails or
309  * dict_size is invalid, NULL is returned.
310  *
311  * The compressed format supported by this decoder is a raw LZMA stream
312  * whose first byte (always 0x00) has been replaced with bitwise-negation
313  * of the LZMA properties (lc/lp/pb) byte. For example, if lc/lp/pb is
314  * 3/0/2, the first byte is 0xA2. This way the first byte can never be 0x00.
315  * Just like with LZMA2, lc + lp <= 4 must be true. The LZMA end-of-stream
316  * marker must not be used. The unused values are reserved for future use.
317  * This MicroLZMA header format was created for use in EROFS but may be used
318  * by others too.
319  */
320 extern struct xz_dec_microlzma *xz_dec_microlzma_alloc(enum xz_mode mode,
321 						       uint32_t dict_size);
322 
323 /**
324  * xz_dec_microlzma_reset() - Reset the MicroLZMA decoder state
325  * @s           Decoder state allocated using xz_dec_microlzma_alloc()
326  * @comp_size   Compressed size of the input stream
327  * @uncomp_size Uncompressed size of the input stream. A value smaller
328  *              than the real uncompressed size of the input stream can
329  *              be specified if uncomp_size_is_exact is set to false.
330  *              uncomp_size can never be set to a value larger than the
331  *              expected real uncompressed size because it would eventually
332  *              result in XZ_DATA_ERROR.
333  * @uncomp_size_is_exact  This is an int instead of bool to avoid
334  *              requiring stdbool.h. This should normally be set to true.
335  *              When this is set to false, error detection is weaker.
336  */
337 extern void xz_dec_microlzma_reset(struct xz_dec_microlzma *s,
338 				   uint32_t comp_size, uint32_t uncomp_size,
339 				   int uncomp_size_is_exact);
340 
341 /**
342  * xz_dec_microlzma_run() - Run the MicroLZMA decoder
343  * @s           Decoder state initialized using xz_dec_microlzma_reset()
344  * @b:          Input and output buffers
345  *
346  * This works similarly to xz_dec_run() with a few important differences.
347  * Only the differences are documented here.
348  *
349  * The only possible return values are XZ_OK, XZ_STREAM_END, and
350  * XZ_DATA_ERROR. This function cannot return XZ_BUF_ERROR: if no progress
351  * is possible due to lack of input data or output space, this function will
352  * keep returning XZ_OK. Thus, the calling code must be written so that it
353  * will eventually provide input and output space matching (or exceeding)
354  * comp_size and uncomp_size arguments given to xz_dec_microlzma_reset().
355  * If the caller cannot do this (for example, if the input file is truncated
356  * or otherwise corrupt), the caller must detect this error by itself to
357  * avoid an infinite loop.
358  *
359  * If the compressed data seems to be corrupt, XZ_DATA_ERROR is returned.
360  * This can happen also when incorrect dictionary, uncompressed, or
361  * compressed sizes have been specified.
362  *
363  * With XZ_PREALLOC only: As an extra feature, b->out may be NULL to skip over
364  * uncompressed data. This way the caller doesn't need to provide a temporary
365  * output buffer for the bytes that will be ignored.
366  *
367  * With XZ_SINGLE only: In contrast to xz_dec_run(), the return value XZ_OK
368  * is also possible and thus XZ_SINGLE is actually a limited multi-call mode.
369  * After XZ_OK the bytes decoded so far may be read from the output buffer.
370  * It is possible to continue decoding but the variables b->out and b->out_pos
371  * MUST NOT be changed by the caller. Increasing the value of b->out_size is
372  * allowed to make more output space available; one doesn't need to provide
373  * space for the whole uncompressed data on the first call. The input buffer
374  * may be changed normally like with XZ_PREALLOC. This way input data can be
375  * provided from non-contiguous memory.
376  */
377 extern enum xz_ret xz_dec_microlzma_run(struct xz_dec_microlzma *s,
378 					struct xz_buf *b);
379 
380 /**
381  * xz_dec_microlzma_end() - Free the memory allocated for the decoder state
382  * @s:          Decoder state allocated using xz_dec_microlzma_alloc().
383  *              If s is NULL, this function does nothing.
384  */
385 extern void xz_dec_microlzma_end(struct xz_dec_microlzma *s);
386 
387 /*
388  * Standalone build (userspace build or in-kernel build for boot time use)
389  * needs a CRC32 implementation. For normal in-kernel use, kernel's own
390  * CRC32 module is used instead, and users of this module don't need to
391  * care about the functions below.
392  */
393 #ifndef XZ_INTERNAL_CRC32
394 #	ifdef __KERNEL__
395 #		define XZ_INTERNAL_CRC32 0
396 #	else
397 #		define XZ_INTERNAL_CRC32 1
398 #	endif
399 #endif
400 
401 /*
402  * If CRC64 support has been enabled with XZ_USE_CRC64, a CRC64
403  * implementation is needed too.
404  */
405 #ifndef XZ_USE_CRC64
406 #	undef XZ_INTERNAL_CRC64
407 #	define XZ_INTERNAL_CRC64 0
408 #endif
409 #ifndef XZ_INTERNAL_CRC64
410 #	ifdef __KERNEL__
411 #		error Using CRC64 in the kernel has not been implemented.
412 #	else
413 #		define XZ_INTERNAL_CRC64 1
414 #	endif
415 #endif
416 
417 #if XZ_INTERNAL_CRC32
418 /*
419  * This must be called before any other xz_* function to initialize
420  * the CRC32 lookup table.
421  */
422 XZ_EXTERN void xz_crc32_init(void);
423 
424 /*
425  * Update CRC32 value using the polynomial from IEEE-802.3. To start a new
426  * calculation, the third argument must be zero. To continue the calculation,
427  * the previously returned value is passed as the third argument.
428  */
429 XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc);
430 #endif
431 
432 #if XZ_INTERNAL_CRC64
433 /*
434  * This must be called before any other xz_* function (except xz_crc32_init())
435  * to initialize the CRC64 lookup table.
436  */
437 XZ_EXTERN void xz_crc64_init(void);
438 
439 /*
440  * Update CRC64 value using the polynomial from ECMA-182. To start a new
441  * calculation, the third argument must be zero. To continue the calculation,
442  * the previously returned value is passed as the third argument.
443  */
444 XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc);
445 #endif
446 
447 #ifdef __cplusplus
448 }
449 #endif
450 
451 #endif
452