1
2
3
4
5
6#include <common.h>
7#include <compiler.h>
8#include <image.h>
9#include <lz4.h>
10#include <linux/kernel.h>
11#include <linux/types.h>
12
13static u16 LZ4_readLE16(const void *src) { return le16_to_cpu(*(u16 *)src); }
14static void LZ4_copy4(void *dst, const void *src) { *(u32 *)dst = *(u32 *)src; }
15static void LZ4_copy8(void *dst, const void *src) { *(u64 *)dst = *(u64 *)src; }
16
17typedef uint8_t BYTE;
18typedef uint16_t U16;
19typedef uint32_t U32;
20typedef int32_t S32;
21typedef uint64_t U64;
22
23#define FORCE_INLINE static inline __attribute__((always_inline))
24
25
26#include "lz4.c"
27
28struct lz4_frame_header {
29 u32 magic;
30 union {
31 u8 flags;
32 struct {
33 u8 reserved0:2;
34 u8 has_content_checksum:1;
35 u8 has_content_size:1;
36 u8 has_block_checksum:1;
37 u8 independent_blocks:1;
38 u8 version:2;
39 };
40 };
41 union {
42 u8 block_descriptor;
43 struct {
44 u8 reserved1:4;
45 u8 max_block_size:3;
46 u8 reserved2:1;
47 };
48 };
49
50
51} __packed;
52
53struct lz4_block_header {
54 union {
55 u32 raw;
56 struct {
57 u32 size:31;
58 u32 not_compressed:1;
59 };
60 };
61
62
63} __packed;
64
65int ulz4fn(const void *src, size_t srcn, void *dst, size_t *dstn)
66{
67 const void *end = dst + *dstn;
68 const void *in = src;
69 void *out = dst;
70 int has_block_checksum;
71 int ret;
72 *dstn = 0;
73
74 {
75 const struct lz4_frame_header *h = in;
76
77 if (srcn < sizeof(*h) + sizeof(u64) + sizeof(u8))
78 return -EINVAL;
79
80
81 if (le32_to_cpu(h->magic) != LZ4F_MAGIC || h->version != 1)
82 return -EPROTONOSUPPORT;
83 if (h->reserved0 || h->reserved1 || h->reserved2)
84 return -EINVAL;
85 if (!h->independent_blocks)
86 return -EPROTONOSUPPORT;
87 has_block_checksum = h->has_block_checksum;
88
89 in += sizeof(*h);
90 if (h->has_content_size)
91 in += sizeof(u64);
92 in += sizeof(u8);
93 }
94
95 while (1) {
96 struct lz4_block_header b;
97
98 b.raw = le32_to_cpu(*(u32 *)in);
99 in += sizeof(struct lz4_block_header);
100
101 if (in - src + b.size > srcn) {
102 ret = -EINVAL;
103 break;
104 }
105
106 if (!b.size) {
107 ret = 0;
108 break;
109 }
110
111 if (b.not_compressed) {
112 size_t size = min((ptrdiff_t)b.size, end - out);
113 memcpy(out, in, size);
114 out += size;
115 if (size < b.size) {
116 ret = -ENOBUFS;
117 break;
118 }
119 } else {
120
121 ret = LZ4_decompress_generic(in, out, b.size,
122 end - out, endOnInputSize,
123 full, 0, noDict, out, NULL, 0);
124 if (ret < 0) {
125 ret = -EPROTO;
126 break;
127 }
128 out += ret;
129 }
130
131 in += b.size;
132 if (has_block_checksum)
133 in += sizeof(u32);
134 }
135
136 *dstn = out - dst;
137 return ret;
138}
139