xref: /linux/lib/decompress_unxz.c (revision 64167246791eb38af4cbe8bc93fc2701c71fd17e)
1 // SPDX-License-Identifier: 0BSD
2 
3 /*
4  * Wrapper for decompressing XZ-compressed kernel, initramfs, and initrd
5  *
6  * Author: Lasse Collin <lasse.collin@tukaani.org>
7  */
8 
9 /*
10  * Important notes about in-place decompression
11  *
12  * At least on x86, the kernel is decompressed in place: the compressed data
13  * is placed to the end of the output buffer, and the decompressor overwrites
14  * most of the compressed data. There must be enough safety margin to
15  * guarantee that the write position is always behind the read position.
16  *
17  * The safety margin for XZ with LZMA2 or BCJ+LZMA2 is calculated below.
18  * Note that the margin with XZ is bigger than with Deflate (gzip)!
19  *
20  * The worst case for in-place decompression is that the beginning of
21  * the file is compressed extremely well, and the rest of the file is
22  * incompressible. Thus, we must look for worst-case expansion when the
23  * compressor is encoding incompressible data.
24  *
25  * The structure of the .xz file in case of a compressed kernel is as follows.
26  * Sizes (as bytes) of the fields are in parenthesis.
27  *
28  *    Stream Header (12)
29  *    Block Header:
30  *      Block Header (8-12)
31  *      Compressed Data (N)
32  *      Block Padding (0-3)
33  *      CRC32 (4)
34  *    Index (8-20)
35  *    Stream Footer (12)
36  *
37  * Normally there is exactly one Block, but let's assume that there are
38  * 2-4 Blocks just in case. Because Stream Header and also Block Header
39  * of the first Block don't make the decompressor produce any uncompressed
40  * data, we can ignore them from our calculations. Block Headers of possible
41  * additional Blocks have to be taken into account still. With these
42  * assumptions, it is safe to assume that the total header overhead is
43  * less than 128 bytes.
44  *
45  * Compressed Data contains LZMA2 or BCJ+LZMA2 encoded data. Since BCJ
46  * doesn't change the size of the data, it is enough to calculate the
47  * safety margin for LZMA2.
48  *
49  * LZMA2 stores the data in chunks. Each chunk has a header whose size is
50  * a maximum of 6 bytes, but to get round 2^n numbers, let's assume that
51  * the maximum chunk header size is 8 bytes. After the chunk header, there
52  * may be up to 64 KiB of actual payload in the chunk. Often the payload is
53  * quite a bit smaller though; to be safe, let's assume that an average
54  * chunk has only 32 KiB of payload.
55  *
56  * The maximum uncompressed size of the payload is 2 MiB. The minimum
57  * uncompressed size of the payload is in practice never less than the
58  * payload size itself. The LZMA2 format would allow uncompressed size
59  * to be less than the payload size, but no sane compressor creates such
60  * files. LZMA2 supports storing incompressible data in uncompressed form,
61  * so there's never a need to create payloads whose uncompressed size is
62  * smaller than the compressed size.
63  *
64  * The assumption, that the uncompressed size of the payload is never
65  * smaller than the payload itself, is valid only when talking about
66  * the payload as a whole. It is possible that the payload has parts where
67  * the decompressor consumes more input than it produces output. Calculating
68  * the worst case for this would be tricky. Instead of trying to do that,
69  * let's simply make sure that the decompressor never overwrites any bytes
70  * of the payload which it is currently reading.
71  *
72  * Now we have enough information to calculate the safety margin. We need
73  *   - 128 bytes for the .xz file format headers;
74  *   - 8 bytes per every 32 KiB of uncompressed size (one LZMA2 chunk header
75  *     per chunk, each chunk having average payload size of 32 KiB); and
76  *   - 64 KiB (biggest possible LZMA2 chunk payload size) to make sure that
77  *     the decompressor never overwrites anything from the LZMA2 chunk
78  *     payload it is currently reading.
79  *
80  * We get the following formula:
81  *
82  *    safety_margin = 128 + uncompressed_size * 8 / 32768 + 65536
83  *                  = 128 + (uncompressed_size >> 12) + 65536
84  *
85  * For comparison, according to arch/x86/boot/compressed/misc.c, the
86  * equivalent formula for Deflate is this:
87  *
88  *    safety_margin = 18 + (uncompressed_size >> 12) + 32768
89  *
90  * Thus, when updating Deflate-only in-place kernel decompressor to
91  * support XZ, the fixed overhead has to be increased from 18+32768 bytes
92  * to 128+65536 bytes.
93  */
94 
95 /*
96  * STATIC is defined to "static" if we are being built for kernel
97  * decompression (pre-boot code). <linux/decompress/mm.h> will define
98  * STATIC to empty if it wasn't already defined. Since we will need to
99  * know later if we are being used for kernel decompression, we define
100  * XZ_PREBOOT here.
101  */
102 #ifdef STATIC
103 #	define XZ_PREBOOT
104 #else
105 #	include <linux/decompress/unxz.h>
106 #endif
107 #ifdef __KERNEL__
108 #	include <linux/decompress/mm.h>
109 #endif
110 #define XZ_EXTERN STATIC
111 
112 #ifndef XZ_PREBOOT
113 #	include <linux/slab.h>
114 #	include <linux/xz.h>
115 #else
116 /*
117  * Use the internal CRC32 code instead of kernel's CRC32 module, which
118  * is not available in early phase of booting.
119  */
120 #define XZ_INTERNAL_CRC32 1
121 
122 /*
123  * For boot time use, we enable only the BCJ filter of the current
124  * architecture or none if no BCJ filter is available for the architecture.
125  */
126 #ifdef CONFIG_X86
127 #	define XZ_DEC_X86
128 #endif
129 #ifdef CONFIG_PPC
130 #	define XZ_DEC_POWERPC
131 #endif
132 #ifdef CONFIG_ARM
133 #	define XZ_DEC_ARM
134 #endif
135 #ifdef CONFIG_SPARC
136 #	define XZ_DEC_SPARC
137 #endif
138 
139 /*
140  * This will get the basic headers so that memeq() and others
141  * can be defined.
142  */
143 #include "xz/xz_private.h"
144 
145 /*
146  * Replace the normal allocation functions with the versions from
147  * <linux/decompress/mm.h>. vfree() needs to support vfree(NULL)
148  * when XZ_DYNALLOC is used, but the pre-boot free() doesn't support it.
149  * Workaround it here because the other decompressors don't need it.
150  */
151 #undef kmalloc
152 #undef kfree
153 #undef vmalloc
154 #undef vfree
155 #define kmalloc(size, flags) malloc(size)
156 #define kfree(ptr) free(ptr)
157 #define vmalloc(size) malloc(size)
158 #define vfree(ptr) do { if (ptr != NULL) free(ptr); } while (0)
159 
160 /*
161  * FIXME: Not all basic memory functions are provided in architecture-specific
162  * files (yet). We define our own versions here for now, but this should be
163  * only a temporary solution.
164  *
165  * memeq and memzero are not used much and any remotely sane implementation
166  * is fast enough. memcpy/memmove speed matters in multi-call mode, but
167  * the kernel image is decompressed in single-call mode, in which only
168  * memmove speed can matter and only if there is a lot of incompressible data
169  * (LZMA2 stores incompressible chunks in uncompressed form). Thus, the
170  * functions below should just be kept small; it's probably not worth
171  * optimizing for speed.
172  */
173 
174 #ifndef memeq
175 static bool memeq(const void *a, const void *b, size_t size)
176 {
177 	const uint8_t *x = a;
178 	const uint8_t *y = b;
179 	size_t i;
180 
181 	for (i = 0; i < size; ++i)
182 		if (x[i] != y[i])
183 			return false;
184 
185 	return true;
186 }
187 #endif
188 
189 #ifndef memzero
190 static void memzero(void *buf, size_t size)
191 {
192 	uint8_t *b = buf;
193 	uint8_t *e = b + size;
194 
195 	while (b != e)
196 		*b++ = '\0';
197 }
198 #endif
199 
200 #ifndef memmove
201 /* Not static to avoid a conflict with the prototype in the Linux headers. */
202 void *memmove(void *dest, const void *src, size_t size)
203 {
204 	uint8_t *d = dest;
205 	const uint8_t *s = src;
206 	size_t i;
207 
208 	if (d < s) {
209 		for (i = 0; i < size; ++i)
210 			d[i] = s[i];
211 	} else if (d > s) {
212 		i = size;
213 		while (i-- > 0)
214 			d[i] = s[i];
215 	}
216 
217 	return dest;
218 }
219 #endif
220 
221 /*
222  * Since we need memmove anyway, we could use it as memcpy too.
223  * Commented out for now to avoid breaking things.
224  */
225 /*
226 #ifndef memcpy
227 #	define memcpy memmove
228 #endif
229 */
230 
231 #include "xz/xz_crc32.c"
232 #include "xz/xz_dec_stream.c"
233 #include "xz/xz_dec_lzma2.c"
234 #include "xz/xz_dec_bcj.c"
235 
236 #endif /* XZ_PREBOOT */
237 
238 /* Size of the input and output buffers in multi-call mode */
239 #define XZ_IOBUF_SIZE 4096
240 
241 /*
242  * This function implements the API defined in <linux/decompress/generic.h>.
243  *
244  * This wrapper will automatically choose single-call or multi-call mode
245  * of the native XZ decoder API. The single-call mode can be used only when
246  * both input and output buffers are available as a single chunk, i.e. when
247  * fill() and flush() won't be used.
248  */
249 STATIC int INIT unxz(unsigned char *in, long in_size,
250 		     long (*fill)(void *dest, unsigned long size),
251 		     long (*flush)(void *src, unsigned long size),
252 		     unsigned char *out, long *in_used,
253 		     void (*error)(char *x))
254 {
255 	struct xz_buf b;
256 	struct xz_dec *s;
257 	enum xz_ret ret;
258 	bool must_free_in = false;
259 
260 #if XZ_INTERNAL_CRC32
261 	xz_crc32_init();
262 #endif
263 
264 	if (in_used != NULL)
265 		*in_used = 0;
266 
267 	if (fill == NULL && flush == NULL)
268 		s = xz_dec_init(XZ_SINGLE, 0);
269 	else
270 		s = xz_dec_init(XZ_DYNALLOC, (uint32_t)-1);
271 
272 	if (s == NULL)
273 		goto error_alloc_state;
274 
275 	if (flush == NULL) {
276 		b.out = out;
277 		b.out_size = (size_t)-1;
278 	} else {
279 		b.out_size = XZ_IOBUF_SIZE;
280 		b.out = malloc(XZ_IOBUF_SIZE);
281 		if (b.out == NULL)
282 			goto error_alloc_out;
283 	}
284 
285 	if (in == NULL) {
286 		must_free_in = true;
287 		in = malloc(XZ_IOBUF_SIZE);
288 		if (in == NULL)
289 			goto error_alloc_in;
290 	}
291 
292 	b.in = in;
293 	b.in_pos = 0;
294 	b.in_size = in_size;
295 	b.out_pos = 0;
296 
297 	if (fill == NULL && flush == NULL) {
298 		ret = xz_dec_run(s, &b);
299 	} else {
300 		do {
301 			if (b.in_pos == b.in_size && fill != NULL) {
302 				if (in_used != NULL)
303 					*in_used += b.in_pos;
304 
305 				b.in_pos = 0;
306 
307 				in_size = fill(in, XZ_IOBUF_SIZE);
308 				if (in_size < 0) {
309 					/*
310 					 * This isn't an optimal error code
311 					 * but it probably isn't worth making
312 					 * a new one either.
313 					 */
314 					ret = XZ_BUF_ERROR;
315 					break;
316 				}
317 
318 				b.in_size = in_size;
319 			}
320 
321 			ret = xz_dec_run(s, &b);
322 
323 			if (flush != NULL && (b.out_pos == b.out_size
324 					|| (ret != XZ_OK && b.out_pos > 0))) {
325 				/*
326 				 * Setting ret here may hide an error
327 				 * returned by xz_dec_run(), but probably
328 				 * it's not too bad.
329 				 */
330 				if (flush(b.out, b.out_pos) != (long)b.out_pos)
331 					ret = XZ_BUF_ERROR;
332 
333 				b.out_pos = 0;
334 			}
335 		} while (ret == XZ_OK);
336 
337 		if (must_free_in)
338 			free(in);
339 
340 		if (flush != NULL)
341 			free(b.out);
342 	}
343 
344 	if (in_used != NULL)
345 		*in_used += b.in_pos;
346 
347 	xz_dec_end(s);
348 
349 	switch (ret) {
350 	case XZ_STREAM_END:
351 		return 0;
352 
353 	case XZ_MEM_ERROR:
354 		/* This can occur only in multi-call mode. */
355 		error("XZ decompressor ran out of memory");
356 		break;
357 
358 	case XZ_FORMAT_ERROR:
359 		error("Input is not in the XZ format (wrong magic bytes)");
360 		break;
361 
362 	case XZ_OPTIONS_ERROR:
363 		error("Input was encoded with settings that are not "
364 				"supported by this XZ decoder");
365 		break;
366 
367 	case XZ_DATA_ERROR:
368 	case XZ_BUF_ERROR:
369 		error("XZ-compressed data is corrupt");
370 		break;
371 
372 	default:
373 		error("Bug in the XZ decompressor");
374 		break;
375 	}
376 
377 	return -1;
378 
379 error_alloc_in:
380 	if (flush != NULL)
381 		free(b.out);
382 
383 error_alloc_out:
384 	xz_dec_end(s);
385 
386 error_alloc_state:
387 	error("XZ decompressor ran out of memory");
388 	return -1;
389 }
390 
391 /*
392  * This function is used by architecture-specific files to decompress
393  * the kernel image.
394  */
395 #ifdef XZ_PREBOOT
396 STATIC int INIT __decompress(unsigned char *in, long in_size,
397 			     long (*fill)(void *dest, unsigned long size),
398 			     long (*flush)(void *src, unsigned long size),
399 			     unsigned char *out, long out_size,
400 			     long *in_used,
401 			     void (*error)(char *x))
402 {
403 	return unxz(in, in_size, fill, flush, out, in_used, error);
404 }
405 #endif
406