LLVM 24.0.0git
Compression.cpp
Go to the documentation of this file.
1//===--- Compression.cpp - Compression implementation ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements compression functions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ScopeExit.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Config/config.h"
19#include "llvm/Support/Error.h"
21#include <limits>
22#if LLVM_ENABLE_ZLIB
23#include <zlib.h>
24#endif
25#if LLVM_ENABLE_ZSTD
26#include <zstd.h>
27#endif
28#if LLVM_ENABLE_LZMA
29#include <lzma.h>
30#endif
31
32using namespace llvm;
33using namespace llvm::compression;
34
36 switch (F) {
39 return nullptr;
40 return "LLVM was not built with LLVM_ENABLE_ZLIB or did not find zlib at "
41 "build time";
44 return nullptr;
45 return "LLVM was not built with LLVM_ENABLE_ZSTD or did not find zstd at "
46 "build time";
47 }
49}
50
53 switch (P.format) {
55 zlib::compress(Input, Output, P.level);
56 break;
58 zstd::compress(Input, Output, P.level, P.zstdEnableLdm);
59 break;
60 }
61}
62
64 uint8_t *Output, size_t UncompressedSize) {
65 switch (formatFor(T)) {
67 return zlib::decompress(Input, Output, UncompressedSize);
69 return zstd::decompress(Input, Output, UncompressedSize);
70 }
72}
73
76 size_t UncompressedSize) {
77 switch (F) {
79 return zlib::decompress(Input, Output, UncompressedSize);
81 return zstd::decompress(Input, Output, UncompressedSize);
82 }
84}
85
88 size_t UncompressedSize) {
89 return decompress(formatFor(T), Input, Output, UncompressedSize);
90}
91
92#if LLVM_ENABLE_ZLIB
93
94static StringRef convertZlibCodeToString(int Code) {
95 switch (Code) {
96 case Z_MEM_ERROR:
97 return "zlib error: Z_MEM_ERROR";
98 case Z_BUF_ERROR:
99 return "zlib error: Z_BUF_ERROR";
100 case Z_STREAM_ERROR:
101 return "zlib error: Z_STREAM_ERROR";
102 case Z_DATA_ERROR:
103 return "zlib error: Z_DATA_ERROR";
104 case Z_OK:
105 default:
106 llvm_unreachable("unknown or unexpected zlib status code");
107 }
108}
109
110bool zlib::isAvailable() { return true; }
111
113 SmallVectorImpl<uint8_t> &CompressedBuffer, int Level) {
114 unsigned long CompressedSize = ::compressBound(Input.size());
115 CompressedBuffer.resize_for_overwrite(CompressedSize);
116 int Res = ::compress2((Bytef *)CompressedBuffer.data(), &CompressedSize,
117 (const Bytef *)Input.data(), Input.size(), Level);
118 if (Res == Z_MEM_ERROR)
119 report_bad_alloc_error("Allocation failed");
120 assert(Res == Z_OK);
121 // Tell MemorySanitizer that zlib output buffer is fully initialized.
122 // This avoids a false report when running LLVM with uninstrumented ZLib.
123 __msan_unpoison(CompressedBuffer.data(), CompressedSize);
124 if (CompressedSize < CompressedBuffer.size())
125 CompressedBuffer.truncate(CompressedSize);
126}
127
129 size_t &UncompressedSize) {
130 int Res = ::uncompress((Bytef *)Output, (uLongf *)&UncompressedSize,
131 (const Bytef *)Input.data(), Input.size());
132 // Tell MemorySanitizer that zlib output buffer is fully initialized.
133 // This avoids a false report when running LLVM with uninstrumented ZLib.
134 __msan_unpoison(Output, UncompressedSize);
135 return Res ? make_error<StringError>(convertZlibCodeToString(Res),
137 : Error::success();
138}
139
142 size_t UncompressedSize) {
143 Output.resize_for_overwrite(UncompressedSize);
144 Error E = zlib::decompress(Input, Output.data(), UncompressedSize);
145 if (UncompressedSize < Output.size())
146 Output.truncate(UncompressedSize);
147 return E;
148}
149
150#else
151bool zlib::isAvailable() { return false; }
153 SmallVectorImpl<uint8_t> &CompressedBuffer, int Level) {
154 llvm_unreachable("zlib::compress is unavailable");
155}
157 size_t &UncompressedSize) {
158 llvm_unreachable("zlib::decompress is unavailable");
159}
161 SmallVectorImpl<uint8_t> &UncompressedBuffer,
162 size_t UncompressedSize) {
163 llvm_unreachable("zlib::decompress is unavailable");
164}
165#endif
166
167#if LLVM_ENABLE_ZSTD
168
169bool zstd::isAvailable() { return true; }
170
171#include <zstd.h> // Ensure ZSTD library is included
172
174 SmallVectorImpl<uint8_t> &CompressedBuffer, int Level,
175 bool EnableLdm) {
176 ZSTD_CCtx *Cctx = ZSTD_createCCtx();
177 if (!Cctx)
178 report_bad_alloc_error("Failed to create ZSTD_CCtx");
179
180 if (ZSTD_isError(ZSTD_CCtx_setParameter(
181 Cctx, ZSTD_c_enableLongDistanceMatching, EnableLdm ? 1 : 0))) {
182 ZSTD_freeCCtx(Cctx);
183 report_bad_alloc_error("Failed to set ZSTD_c_enableLongDistanceMatching");
184 }
185
186 if (ZSTD_isError(
187 ZSTD_CCtx_setParameter(Cctx, ZSTD_c_compressionLevel, Level))) {
188 ZSTD_freeCCtx(Cctx);
189 report_bad_alloc_error("Failed to set ZSTD_c_compressionLevel");
190 }
191
192 unsigned long CompressedBufferSize = ZSTD_compressBound(Input.size());
193 CompressedBuffer.resize_for_overwrite(CompressedBufferSize);
194
195 size_t const CompressedSize =
196 ZSTD_compress2(Cctx, CompressedBuffer.data(), CompressedBufferSize,
197 Input.data(), Input.size());
198
199 ZSTD_freeCCtx(Cctx);
200
201 if (ZSTD_isError(CompressedSize))
202 report_bad_alloc_error("Compression failed");
203
204 __msan_unpoison(CompressedBuffer.data(), CompressedSize);
205 if (CompressedSize < CompressedBuffer.size())
206 CompressedBuffer.truncate(CompressedSize);
207}
208
210 size_t &UncompressedSize) {
211 const size_t Res = ::ZSTD_decompress(
212 Output, UncompressedSize, (const uint8_t *)Input.data(), Input.size());
213 UncompressedSize = Res;
214 if (ZSTD_isError(Res))
215 return make_error<StringError>(ZSTD_getErrorName(Res),
217 // Tell MemorySanitizer that zstd output buffer is fully initialized.
218 // This avoids a false report when running LLVM with uninstrumented ZLib.
219 __msan_unpoison(Output, UncompressedSize);
220 return Error::success();
221}
222
225 size_t UncompressedSize) {
226 Output.resize_for_overwrite(UncompressedSize);
227 Error E = zstd::decompress(Input, Output.data(), UncompressedSize);
228 if (UncompressedSize < Output.size())
229 Output.truncate(UncompressedSize);
230 return E;
231}
232
233#else
234bool zstd::isAvailable() { return false; }
236 SmallVectorImpl<uint8_t> &CompressedBuffer, int Level,
237 bool EnableLdm) {
238 llvm_unreachable("zstd::compress is unavailable");
239}
241 size_t &UncompressedSize) {
242 llvm_unreachable("zstd::decompress is unavailable");
243}
246 size_t UncompressedSize) {
247 llvm_unreachable("zstd::decompress is unavailable");
248}
249#endif
250
251#if LLVM_ENABLE_LZMA
252
253bool xz::isAvailable() { return true; }
254
255// Returns a C string rather than a StringRef because every caller feeds the
256// result to a printf-style "%s", which requires NUL termination.
257static const char *convertLZMACodeToString(lzma_ret Code) {
258 switch (Code) {
259 case LZMA_STREAM_END:
260 return "lzma error: LZMA_STREAM_END";
261 case LZMA_NO_CHECK:
262 return "lzma error: LZMA_NO_CHECK";
263 case LZMA_UNSUPPORTED_CHECK:
264 return "lzma error: LZMA_UNSUPPORTED_CHECK";
265 case LZMA_GET_CHECK:
266 return "lzma error: LZMA_GET_CHECK";
267 case LZMA_MEM_ERROR:
268 return "lzma error: LZMA_MEM_ERROR";
269 case LZMA_MEMLIMIT_ERROR:
270 return "lzma error: LZMA_MEMLIMIT_ERROR";
271 case LZMA_FORMAT_ERROR:
272 return "lzma error: LZMA_FORMAT_ERROR";
273 case LZMA_OPTIONS_ERROR:
274 return "lzma error: LZMA_OPTIONS_ERROR";
275 case LZMA_DATA_ERROR:
276 return "lzma error: LZMA_DATA_ERROR";
277 case LZMA_BUF_ERROR:
278 return "lzma error: LZMA_BUF_ERROR";
279 case LZMA_PROG_ERROR:
280 return "lzma error: LZMA_PROG_ERROR";
281 default:
282 llvm_unreachable("unknown or unexpected lzma status code");
283 }
284}
285
286/// Read the uncompressed size recorded in the xz stream's index.
287static Expected<uint64_t> getUncompressedSize(ArrayRef<uint8_t> Input) {
288 if (Input.size() < LZMA_STREAM_HEADER_SIZE)
289 return createStringError(
290 "size of xz-compressed blob (%zu bytes) is smaller than the "
291 "LZMA_STREAM_HEADER_SIZE (%zu bytes)",
292 Input.size(), size_t(LZMA_STREAM_HEADER_SIZE));
293
294 // Decode the xz footer.
295 lzma_stream_flags FooterFlags{};
296 lzma_ret Ret = lzma_stream_footer_decode(
297 &FooterFlags, Input.take_back(LZMA_STREAM_HEADER_SIZE).data());
298 if (Ret != LZMA_OK)
299 return createStringError("lzma_stream_footer_decode()=%s",
300 convertLZMACodeToString(Ret));
301
302 // A stream is the header, block data, index and stream footer
303 uint64_t MinSize = FooterFlags.backward_size + 2 * LZMA_STREAM_HEADER_SIZE;
304 if (Input.size() < MinSize)
305 return createStringError(
306 "xz-compressed buffer size (%zu bytes) too small (required at "
307 "least %" PRIu64 " bytes)",
308 Input.size(), MinSize);
309
310 // Decode xz index.
311 // liblzma stores null on failure, and lzma_index_end() ignores null.
312 lzma_index *Index = nullptr;
313 llvm::scope_exit FreeIndex([&] { lzma_index_end(Index, nullptr); });
314 uint64_t MemLimit = UINT64_MAX;
315 size_t InPos = 0;
316 Ret = lzma_index_buffer_decode(
317 &Index, &MemLimit, nullptr,
318 Input.take_back(LZMA_STREAM_HEADER_SIZE + FooterFlags.backward_size)
319 .data(),
320 &InPos, Input.size());
321 if (Ret != LZMA_OK)
322 return createStringError("lzma_index_buffer_decode()=%s",
323 convertLZMACodeToString(Ret));
324
325 return lzma_index_uncompressed_size(Index);
326}
327
329 SmallVectorImpl<uint8_t> &Output) {
330 // Hand back nothing unless the whole stream decodes.
331 Output.clear();
332
333 Expected<uint64_t> UncompressedSize = getUncompressedSize(Input);
334 if (!UncompressedSize)
335 return UncompressedSize.takeError();
336
337 if (*UncompressedSize > std::numeric_limits<size_t>::max())
338 return createStringError("xz uncompressed size (%" PRIu64
339 " bytes) exceeds addressable memory",
340 *UncompressedSize);
341
342 // Concatenated streams are unsupported: liblzma decodes only the first and
343 // still reports LZMA_OK, leaving the rest of Output zero-filled.
344 Output.resize(static_cast<size_t>(*UncompressedSize));
345 uint64_t MemLimit = UINT64_MAX;
346 size_t InPos = 0;
347 size_t OutPos = 0;
348 lzma_ret Ret = lzma_stream_buffer_decode(
349 &MemLimit, /*flags=*/0, nullptr, Input.data(), &InPos, Input.size(),
350 Output.data(), &OutPos, Output.size());
351 if (Ret != LZMA_OK) {
352 Output.clear();
353 return createStringError("lzma_stream_buffer_decode()=%s",
354 convertLZMACodeToString(Ret));
355 }
356
357 return Error::success();
358}
359
360#else
361
362bool xz::isAvailable() { return false; }
364 SmallVectorImpl<uint8_t> &Output) {
365 llvm_unreachable("xz::decompress is unavailable");
366}
367
368#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define __msan_unpoison(p, size)
Definition Compiler.h:584
#define F(x, y, z)
Definition MD5.cpp:54
#define T
#define P(N)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void truncate(size_type N)
Like resize, but requires that N is less than size().
void resize(size_type N)
pointer data()
Return a pointer to the vector's buffer, even if empty().
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI bool isAvailable()
Return true if LLVM was built with LZMA support (LLVM_ENABLE_LZMA).
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &Output)
Decompress an xz stream.
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression, bool EnableLdm=false)
LLVM_ABI const char * getReasonIfUnsupported(Format F)
LLVM_ABI Error decompress(DebugCompressionType T, ArrayRef< uint8_t > Input, uint8_t *Output, size_t UncompressedSize)
Format formatFor(DebugCompressionType Type)
LLVM_ABI void compress(Params P, ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &Output)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
DebugCompressionType
Definition Compression.h:28
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
LLVM_ABI void report_bad_alloc_error(const char *Reason, bool GenCrashDiag=true)
Reports a bad alloc error, calling any user defined bad alloc error handler.